Ok, I can't believe I'm actually asking this, because it seems like it should be a very very simple problem, but for some reason, I just can't get this to work out right.
I'm trying to make a stopwatch in C#, accurate to hundredths of a second. However, I just can't get it to keep time accurately!
I create a timer with an eventhandler, and set its interval to 10, so it should fire every hundredth of a second.
Timer clock = new Timer();
int hs_elapsed = 0;
clock.Interval = 10;
//when the timer is started:
clock.Start();
clock.Tick += new EventHandler(clock_Tick);
Then, here is what is happening when the event fires:
hs_elapsed++;
int hs = hs_elapsed%100;
int seconds_elapsed = hs_elapsed / 100;
int seconds = seconds_elapsed % 60;
int minutes_elapsed = seconds_elapsed / 60;
int minutes = minutes_elapsed % 60;
textBoxTime.Text = minutes.ToString("00") + ":" + seconds.ToString("00") + "." + hs.ToString("00");
I'm guessing I'm doing something wrong in the way that I calculate the seconds.

1 answers
It sounds like you're using the System.Windows.Forms.Timer which is limited to an accuracy of 55 ms and runs on the UI thread which means that it's Tick event may not necessarily fire when it should because of the need to service other events on that thread.
The System.Timers.Timer and System.Threading.Timer are more accurate (around 10 to 20 ms) and their Tick and Elapsed events (respectively) fire on thread pool threads rather than the UI thread.
For even greater accuracy (1 to 2ms), there's also the StopWatch class. In fact, to be guaranteed 10 ms accuracy (1/100th second) you'll have to use this unless you're happy to P/Invoke the Windows multimedia timer which has similar accuracy.
answered 2 years ago by:
17279
33
Sound like just what I needed, thanks!