Search code examples
c#wpfdispatchertimer

DispatcherTimer with interval 0,0,1 is not exactly 1 second?


(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?


Solution

  • 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.