I want to have a running timer in my app which displays the seconds elapsed upto 2 decimal places e.g. 2.31 seconds. I’m using System.Threading.Timer for this and I’m setting the Timer object to call refreshTimeBox() function every 10 milliseconds (because I want the seconds upto 2 decimal places). But, the timer lags behind. And as the time passed increases, it lags more and more behind. I’m guessing its because refreshTimeBox() is taking too long to complete. But, I also tried calling refreshTimeBox() every 100 milliseconds instead. The timer still lags. The only difference is that the lag becomes noticeable after a longer time in this case than in the case where I use 10 milliseconds as interval. I have the following code to initialize the timer:
timer = new Timer(refreshTimeBox, null, 0, 10);
The following is the code for refreshTimeBox:
public void refreshTimeBox(object param)
{
time += 0.01f;
Dispatcher.BeginInvoke(WriteTimeBox);
}
The following is the code for WriteTimeBox:
public void WriteTimeBox()
{
TimeBar.Text = time.ToString("0.00");
}
time is the variable which stores the time elapsed and TimeBar is the text box which is being updated.
I want as accurate a timer as possible. Please help me with this. Thanks.
If you want to display the amount of time that has elapsed since a particular event in the past, then the best way to do that is to store the time at “time zero”, e.g.
startTime, and then, in your timer event, computer the time that has elapsed by subtractingstartTimefrom the current time, and displaying the difference.You can’t rely on timer events being delivered at exact intervals. This isn’t a realtime system. Added to which, you should be aware that
BeginInvokeis likely requesting that the method call occur on a different thread to the current one, and that different thread may not be able to dispatch that method call at the current time.