I have an application that requires multiple countdown timers to run (some simultaneously). They also update UI elements with the time remaining on the countdown. I have tried using DispatcherTimer for it's easy way to interact with UI elements. However, over a 300 second countdown, it becomes out of sync with real time (because of the heavy UI updating) to the point that I get 30 seconds left on the timer when it should be 0.
I then tried switching to a System.Threading.Timer (code below). Now, the timer is spot-on and in sync with real life time. However, the Timer stops ticking after a random number of ticks (between 3 seconds and 60 seconds). I suspect it's either the garbage collector kicking in, or the Invoke (used for updating the UI) but don't really have the knowledge to continue down this path. Can anybody give me any insight as to why the timer randomly stops ?
private int counter = 500;
private void btnTopBlue_Click(object sender, RoutedEventArgs e)
{
btnTopBlue.Content = counter.ToString();
Timer dt = new Timer(topBlue_Tick, null, 1000, 1000);
}
private void topBlue_Tick(object sender)
{
if (counter > 0)
{
counter--;
Dispatcher.BeginInvoke(() => btnTopBlue.Content = counter.ToString());
}
else
((Timer)sender).Dispose();
}