Search code examples
c#wpfdatetimetimedispatchertimer

WPF - A more accurate Timer


I'm new to CS and WPF. I'm going to get a DateTime object and set it as the beginning of my timer. But I used DispatcherTimer.Tick. I can feel it inaccurate with a little care and playing with window controls. It apparently its in a single thread beside other functions of program.

 DispatcherTimer timer = new DispatcherTimer();
 timer.Interval = TimeSpan.FromSeconds(1);
 timer.Tick += timer_Tick;
 timer.Start();

 void timer_Tick(object sender, EventArgs e)
 {  
     dateTime = dateTime.AddSeconds(1);
     TimeTb.Text = dateTime.ToLongTimeString();
 }

Is there another method to use for a more accurate timer?


Solution

  • Definitely. Take a look at the System.Diagnostics.Stopwatch class. You're re-inventing the wheel!