Reputation: 61
I want to make a timer to update the UI counter using DispatcherTimer class.
Here's my code:
private static DispatcherTimer timer;
private static int count;
//counter is TextBlock in WPF xaml
private void countdownBtn_Click(object sender, RoutedEventArgs e)
{
count = 3;
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
timer.Tick += CountDown;
timer.Start();
}
private void CountDown(object sender, EventArgs e)
{
//if counter becomes 0, stop the counter
if (count <= 0)
{
counter.Visibility = Visibility.Hidden;
timer.Stop();
return;
}
if (counter.Visibility == Visibility.Hidden)
{
counter.Text = count.ToString();
counter.Visibility = Visibility.Visible;
}
else
{
count--;
counter.Visibility = Visibility.Hidden;
}
}
This code works fine if I click the button one time and wait it to complete its task for 3 seconds. But if I clicked the button 2 times in a row, it will continue following this:
timer.Stop()
is executed ( it will enter loop CountDown
-> if(count<=0)
-> timer.Stop()
-> return;
-> CountDown
-> if(count<=0)
-> ... ).And if I want to do something after the timer is stopped, where should I modify my code?
Upvotes: 0
Views: 668
Reputation: 1510
Every time you click the button a new DispatcherTimer is created with the previous ones still running.
You should stop and then dispose the old timer before create new ones.
Upvotes: 1