I am working on a very simple stopwatch using WPF, but the stopwatch System.Diagnosticswas very slow and not reliable at all, compared to my system clock every 1 second from my application was 3 seconds on the actual clock.
I made several searches that the stopwatch is slow, found a lot of results, but there is no solution for it, so I decided to come up with my own counter.
Here is an example of what I came up with:
System.Windows.Threading.DispatcherTimer _update;
DateTime _started;
bool isRunning = false;
Update thread:
_update = new System.Windows.Threading.DispatcherTimer(new TimeSpan(0, 0, 0, 0, 1), System.Windows.Threading.DispatcherPriority.Normal, delegate
{
if (isRunning)
iTimer.Content = new DateTime((DateTime.Now - _started).Ticks).ToString("HH:mm:ss");
}, this.Dispatcher);
I have two buttons, bToggle, which can be started, stopped and resumed, and the other button is called bReset.
private void bReset_Click(object sender, RoutedEventArgs e)
{
isRunning = false;
iTimer.Content = "00:00:00";
bToggle.Content = "Start";
}
private void bToggle_Click(object sender, RoutedEventArgs e)
{
if ((string)bToggle.Content == "Start")
{
isRunning = true;
_started = DateTime.Now;
bToggle.Content = "Stop";
}
else if ((string)bToggle.Content == "Resume")
{
isRunning = true;
bToggle.Content = "Stop";
}
else
{
isRunning = false;
bToggle.Content = "Resume";
}
}
It works fine and reset, but since I use the actual time, if I stop and resume, it will skip seconds to the actual time.
, ?