DispatchTimer不按时执行 [英] DispatchTimer does not execute on time

查看:504
本文介绍了DispatchTimer不按时执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码在C#中使用DispatchTimer时钟应用程序,但由于某些原因我的时钟似乎跳过1秒飘飞。

I'm coding a clock app using DispatchTimer in c#, but for some reasons my clock seems to skip 1 second every now and then.

如。 52S - > 54S跳过53S

eg. 52s -> 54s skipping 53s.

在我看来,计时器不执行完全相同每秒

Seems to me that the timer does not execute exactly every second.

DispatcherTimer timer = new DispatcherTimer();

timer.Tick += DispatcherTimerEventHandler;

timer.Interval = new TimeSpan(0, 0, 0, 0, 1000);

timer.Interval = new TimeSpan(0, 0, 0, 1);



双方还没有工作。

Both also don't work.

推荐答案

基本上你的做法是错误的。不要一秒添加到基于任何一种计时器的时间跨度(或任何种类计数器),因为在Windows中,计时器不保证火在准确的时间间隔。使用这种方法会导致漂过更长的时间。

Basically your approach is wrong. Don't add "one second" to a TimeSpan (or any kind of counter) based on any kind of timer, because in Windows, timers aren't guaranteed to fire at the exact interval. Using that approach will result in "drift" over longer periods of time.

相反,存储一个DateTime开始值,减去从当前的日期时间获得时间跨度代表了多少时间,因为开始数已超过。这种做法也不会不管你如何经常更新时钟。你可以更新第二个,或者每分钟一次,并返回仍然是正确的时间跨度10倍。

Instead, store a DateTime "start" value and subtract that from the current DateTime to get a TimeSpan representing how much time has transpired since "start". With that approach it won't matter how often you update the clock. You could update 10 times a second, or once a minute, and the TimeSpan returned will still be correct.

另一种方法是使用秒表类。它从它的消逝()属性返回一个时间跨度封装上述过程为您服务。

An alternative is to use the Stopwatch class. It encapsulates the above process for you by returning a TimeSpan from its Elapsed() property.

通过上述两种方法中,它不会不管多久定时器火灾,因为它会保持精确的时间独立于定时频率/时序的。

With either of the two approaches above, it wouldn't matter how often the Timer fires as it will keep accurate time independent of the Timer frequency/timing.

这篇关于DispatchTimer不按时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆