0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Phree
  • 5
  • 5
  • How "accurate" does your timer need to be? ~15ms of resolution is plenty good for 99% of use cases. Ignoring anything else, https://stackoverflow.com/questions/3744032/why-are-net-timers-limited-to-15-ms-resolution will probably shed some light for you. – dlev Jul 17 '18 at 20:26
  • 1
    The DispatcherTimer is only useful to get the Text property updated periodically. Its actual interval is not critical, albeit that when you use *exactly* one second then you get to see what the Nyquist sampling theorem says. Using 100 msec is a reasonable compromise to human eyes. – Hans Passant Jul 17 '18 at 20:38
  • Have a look at this thread: https://stackoverflow.com/questions/51039348/show-current-time-wpf/51043116#51043116 – aydjay Jul 18 '18 at 06:50

2 Answers2

2

Do not add up seconds. This is accurate:

private TimeSpan offset;

void timer_Tick(object sender, EventArgs e)
{  
    TimeTb.Text = (DateTime.Now - offset).ToLongTimeString();
}

If you want to show the time elapsed since a start time:

private DateTime start = DateTime.Now;

void timer_Tick(object sender, EventArgs e)
{  
    TimeTb.Text = (DateTime.Now - start).ToString();
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Then subtract an appropriate TimeSpan. Your approach requires *infinite* accuracy, something that doesn't exist. – Clemens Jul 17 '18 at 21:24
1

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

Haney
  • 32,775
  • 8
  • 59
  • 68
  • I could not take the right way to use this class. Can u show an example? – Phree Jul 17 '18 at 20:52
  • 1
    @F4125h4d: Did you look? Sorry, but the help for the class includes a sample that pretty much shows everything. Create a Stopwatch, call Start on it, call Stop, then get myStopwatch.Elapsed and turn it into a TimeSpan object. I could write some code, but it would look an awful lot like that sample.https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx – Flydog57 Jul 17 '18 at 21:29