c# - 如何在 c# WPF 中停止 DispatcherTimer
问题描述
我正在检查时间和时间是否等于我想要停止调度程序的时间。
但它不起作用。调用后定时器仍在工作Stop()
。
private void startTime(bool what)
{
vartimer = new DispatcherTimer();
if (!what)
{
MessageBox.Show("Start");
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += setTime;
timer.Start();
}
if (what)
{
MessageBox.Show("Stop");
timer.Stop();
}
}
当它启动时,它会显示开始文本。当它应该停止时,它应该显示停止文本,但它仍在工作。
我做错什么了吗?
timer.stop();
应该停止Dispatcher
吧?
解决方案
定义DispacherTimer
外部方法:
DispatcherTimer timer = new DispatcherTimer();
private void startTime(bool what)
{
if (what == false)
{
MessageBox.Show("Start");
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick -= setTime;
timer.Tick += setTime;
timer.Start();
}
if (what == true)
{
MessageBox.Show("Stop");
timer.Stop();
}
}
DispacherTimer
在您当前的代码中,每次调用该方法时,您都会创建一个新实例。
推荐阅读
- laravel - 如何获取要更新的日期的ID
- macos - 是否有在 Mac 上显示毫秒的视频播放器?
- angular - 究竟什么时候需要 compileComponents?
- pine-script - 自动缩放垂直线宽
- java - 当数据存储在堆栈中时,为什么我的函数没有返回堆栈(自制堆栈类)?
- android - 如何在 Android Studio For Android Noutgat 及以下的图像视图中放置图像
- typescript - 编译打字稿文件在vs代码中创建空的js文件
- dart - 颤振,“:”是什么?
- apache-kafka - MockSchemaRegistryClient 未注册 avro 架构:无法从架构注册表中获取架构
- javascript - 赛普拉斯:未捕获的类型错误:无法读取未定义的属性-(JSON 文件)