DiSiZ
DiSiZ

Reputation: 43

C# DispatcherTimer Issue

I have an issue with the WPF Timer.

Here's my code :

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

As you can see the interval is 1 minute. But when i start my timer, after 1 hour i have a 10 seconde delay. So, i guess it the treatment of my code who make this delay, but i really need a fix timer, without any shift.

Sorry for your eyes !!

Upvotes: 1

Views: 752

Answers (1)

Peter Huber
Peter Huber

Reputation: 3312

The delay is caused by the WPF GUI thread, which runs all WPF code, like rendering and the DispatcherTimer.Tick event. The rendering has a higher priority than a DispatcherTimer with default priority. So when at the time your Tick is supposed to run also some rendering is needed, the rendering gets executed first and delays your Tick by x milliseconds. This is not too bad, but unfortunately these delays can accumulate over time, if you leave the DispatcherTimer.Interval constant. You can improve the precision of the DispatcherTimer by shortening the DispatcherTimer.Interval for every x milliseconds delay like this:

const int constantInterval = 100;//milliseconds

private void Timer_Tick(object? sender, EventArgs e) {
  var now = DateTime.Now;
  var nowMilliseconds = (int)now.TimeOfDay.TotalMilliseconds;
  var timerInterval = constantInterval - 
   nowMilliseconds%constantInterval + 5;//5: sometimes the tick comes few millisecs early
  timer.Interval = TimeSpan.FromMilliseconds(timerInterval);

For a more detail explanation see my article on CodeProject: Improving the WPF DispatcherTimer Precision

Upvotes: 0

Related Questions