I found that if you want to display changes every second, you should try to make changes every tenth of a second so that it seems continuous to the user - perhaps even more often than that.
Now I would completely avoid using a background worker. Instead, I would use the Microsoft Reactive Framework (NuGet "Rx-Main" or "Rx-WinForms" in your case).
Here is the basic code for this:
var start = DateTimeOffset.Now; var subscription = Observable .Interval(TimeSpan.FromSeconds(0.1)) .Select(x => DateTimeOffset.Now.Subtract(start).TotalSeconds) .Select(x => (int)x) .DistinctUntilChanged() .ObserveOn(this) .Subscribe(x => this.label1.Text = x.ToString());
This code creates a timer ( .Interval(...) ) that fires every tenth of a second. Then it calculates the time in seconds since the code was run, turns it into an integer, and discards all consecutive values โโthat are the same. Finally, it observes the observable in the user interface stream ( .ObserveOn(this) ), and then subscribes by assigning a value (in my case) to the label in my form - you can use any type of control that you like.
To stop the subscription, simply do the following:
subscription.Dispose();
He will clean everything right.
The code should be readable if you are not familiar with the Reactive Framework.
Now I used DateTimeOffset instead of Stopwatch , as you do not need high-resolution synchronization for updates occurring every second. Nothing would stop you using Stopwatch if you wanted to.
source share