一旦我多次启动 WPF DispatcherTimer 就不会停止工作
WPF DispatcherTimer not stop working once I started it more than once
我想制作一个定时器来使用 DispatcherTimer class 更新 UI 计数器。
这是我的代码:
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;
}
}
如果我单击按钮一次并等待它完成任务 3 秒,则此代码可以正常工作。但是如果我连续点击按钮 2 次,它将继续如下:
- 如果我单击该按钮,计数器将更新超过 1 个线程(使其比平时更快地可见和隐藏)。
- 即使执行了
timer.Stop()
也会继续工作(会进入循环CountDown
-> if(count<=0)
-> timer.Stop()
-> return;
- > CountDown
-> if(count<=0)
-> ...).
如果我想在计时器停止后做一些事情,我应该在哪里修改我的代码?
每次单击按钮时,都会创建一个新的 DispatcherTimer,之前的 DispatcherTimer 仍然 运行。
您应该停止并在创建新计时器之前处理掉旧计时器。
我想制作一个定时器来使用 DispatcherTimer class 更新 UI 计数器。
这是我的代码:
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;
}
}
如果我单击按钮一次并等待它完成任务 3 秒,则此代码可以正常工作。但是如果我连续点击按钮 2 次,它将继续如下:
- 如果我单击该按钮,计数器将更新超过 1 个线程(使其比平时更快地可见和隐藏)。
- 即使执行了
timer.Stop()
也会继续工作(会进入循环CountDown
->if(count<=0)
->timer.Stop()
->return;
- >CountDown
->if(count<=0)
-> ...).
如果我想在计时器停止后做一些事情,我应该在哪里修改我的代码?
每次单击按钮时,都会创建一个新的 DispatcherTimer,之前的 DispatcherTimer 仍然 运行。
您应该停止并在创建新计时器之前处理掉旧计时器。