To Show a timer for how Long a specific process runs I'm using a Background worker to update an execution time Label. Naturally this should be done every second so that the user sees that it increases consistently.
After trying around a bit and failing utterly I went down the road that I'm checking every 150 milliseconds if the next second is already there and then I update the Display.
private void ExecutionTimerBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Stopwatch executionTime = new Stopwatch();
double lastUpdateAtSeconds = 0;
executionTime.Start();
while (!ExecutionTimerBackgroundWorker.CancellationPending)
{
Thread.Sleep(150); // Sleep for some while to give other threads time to do their stuff
if (executionTime.Elapsed.TotalSeconds > lastUpdateAtSeconds + 1) // Update the Execution time display only once per second
{
ExecutionTimerBackgroundWorker.ReportProgress(0, executionTime.Elapsed); // Update the Execution time Display
lastUpdateAtSeconds = executionTime.Elapsed.TotalSeconds;
}
}
executionTime.Stop();
}
private void ExecutionTimerBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Update the display to the execution time in Minutes:Seconds format
ExecutionTimeLabel.Text = ((TimeSpan) e.UserState).ToString(@"mm\:ss");
}
Now this seems to me a bit inefficient as I run it every 150 milliseconds to just look "hey has the next second already arrived or not". I also tried a different Approach already where I calculate how much time is needed until the next second but at that one I had a few instances where a jump by 2 instead of 1 second each in the Display happened.
So my question here is: Is there any more efficient way to do this? Or is that already how it should be done?