【发布时间】:2015-06-02 11:33:33
【问题描述】:
当您在 DispatcherTimer 中将属性 IsEnabled 设置为 false 时,是否假定计时器在后台保持其状态,或者改为停止并重置?在以下示例中,定时器间隔为 5 秒,如果您运行应用程序并在 4 秒时单击按钮以禁用定时器,并且如果在 7 秒时再次单击按钮以启用它(例如),则定时器事件不是在 8 秒后一秒触发,而是在 12 秒 = 7 秒 + 5 秒触发。似乎 timer.IsEnabled=false 重置了计时器间隔。禁用时有任何替代方法保持计时器状态吗?
应用程序有两个标签 timerLabel 和 statusLabel 以及按钮。我在这里没有足够的声望点来发布图片。
namespace WpfApplication1 {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
int ticksCounter = 0;
System.Windows.Threading.DispatcherTimer timer;
private void Window_Loaded(object sender, RoutedEventArgs e) {
timer = new System.Windows.Threading.DispatcherTimer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = new TimeSpan(0, 0, 0, 5, 0); // Sets 5 s. interval
timer.Start();
}
private void timer_Tick(object sender, EventArgs e) {
ticksCounter ++;
timeLabel.Content = "Ticks = " + ticksCounter.ToString();
}
private void button_Click(object sender, RoutedEventArgs e) {
if (timer.IsEnabled) {
timer.IsEnabled = false;
statusLabel.Content = "OFF";
boton.Content = "Enable";
}
else {
timer.IsEnabled = true;
statusLabel.Content = "ON";
boton.Content = "Disable";
}
}
}
}
【问题讨论】:
-
您是否尝试过使用
.Stop()? -
这个答案应该对你有帮助:stackoverflow.com/questions/3163300/…
-
那个答案似乎是错误的。 IsEnabled=true 重置计时器。