timer is not working well with TimeSpan from milli

2019-09-03 15:09发布

问题:

I am working on my app for Windows Phone 8 and i created a DispatcherTimer

DispatcherTimer Timer= new DispatcherTimer();
 private int TimePass;
 public TapFast()
    {
        TimePass = 0;
        Timer.Tick += new EventHandler(TimePassTick);
        Timer.Interval = TimeSpan.FromMilliseconds(1);
        InitializeComponent();
    }

 public void TimePassTick(Object sender, EventArgs args)
    {

         TimePass++;

         TimeSpan t = TimeSpan.FromMilliseconds(TimePass);
         string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D4}ms",
                                 t.Hours,
                                 t.Minutes,
                                 t.Seconds,
                                 t.Milliseconds);


         time.Text = answer;
     }

When i start the timer , i don't get the right result in the TextBlock

1 second = 1000 milliseconds

I must see a value of 0 increases to 1000 in 1 second but it takes like 18-20 seconds to get to 1000ms

what is the problem ?

回答1:

Windows and the associated APIs are not "real time". Your timer interval is so small that there's no way for Windows to service it on the schedule you're asking for.

With non-real-time OS and APIs, you can't assume that the timer is actually signaled on exactly the interval you asked for. You need to keep track of the actual time yourself (e.g. using the System.Diagnostics.Stopwatch class) and accommodate variations you experience.