문제

(Using WPF)

In a small application that I wrote, I am using some count-down timers. For this I have used the DispatcherTimer.

counter01 = new DispatcherTimer();
counter01.Tick += new EventHandler(counter01_Tick);
counter01.Interval = new TimeSpan(0, 0, 1);

But now when I test/use the program, I have noticed that when it's set to (for example) 60 minutes count-down, it gets a few minutes off compared to the real world time.

Could it be that for some reason DispatcherTimer is not always exactly 1 second if I use it like I did above?

도움이 되었습니까?

해결책

Timers like this will never be absolutely exact. After all, it's got to run on the dispatcher thread - what would you expect to happen if the dispatcher is busy processing some other thread at the same time?

It's likely to be close enough to be visibly ticking at about once per second - you should just take the current time and subtract that from the "target" time (or use a Stopwatch) to get a fairly-accurate count-down instead of just counting the number of times the timer has ticked.

다른 팁

MSDN states that (regarding DispatcherTimer)

Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs.

For every Tick event, the timer will be off by an indeterminate amount of time. For 1 hr (3600 ticks), this will add up. If you set the timer interval to 1 hr, I would expect the error to be much less (although in theory, the dispatcher could be so busy during that one tick that the error is still greater than the other case).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top