我想使用DispatcherTimer类创建一个计时器来更新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秒钟,此代码可以正常工作。但如果我连续两次点击该按钮,它将继续执行此操作:
timer.Stop()
执行后它仍将继续有效(它将进入循环CountDown
- &gt; if(count<=0)
- &gt; timer.Stop()
- &gt; return;
- &gt; CountDown
- &gt; if(count<=0)
- &gt; ...)。如果我想在计时器停止后做某事,我应该在哪里修改我的代码?
答案 0 :(得分:1)
每次单击该按钮时,都会创建一个新的DispatcherTimer,并且之前仍在运行。
您应该在创建新计时器之前停止然后处置旧计时器。