lvlack
lvlack

Reputation: 61

WPF DispatcherTimer not stop working once I started it more than once

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:

  1. If I click the button, the counter will be updated with more than 1 threads (make it visible and hidden faster than usual).
  2. It will continue working even after 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

Answers (1)

Giangregorio
Giangregorio

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

Related Questions