timer is not working well with TimeSpan from milliseconds

血红的双手。 提交于 2019-12-13 05:16:29

问题


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.



来源:https://stackoverflow.com/questions/26703794/timer-is-not-working-well-with-timespan-from-milliseconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!