如何在c#WPF中停止Dispatchermer
我正在检查时间和时间是否等于我想要停止调度员的某个时间 但它不起作用。调用如何在c#WPF中停止Dispatchermer,c#,wpf,dispatchertimer,C#,Wpf,Dispatchertimer,我正在检查时间和时间是否等于我想要停止调度员的某个时间 但它不起作用。调用Stop()后,计时器仍在工作 当它开始时,它显示开始文本。当它应该停止时,它应该显示停止文本,但它仍在工作 我做错什么了吗 timer.stop(); 应该停止调度程序,对吗?您的调度程序实例应该是类的私有字段,因为每次调用startTime(…),您都在创建一个已启动但从未停止的调度程序类的新实例。下面是一个可以做的示例: public class YourClass : IDisposable { priv
Stop()
后,计时器仍在工作
当它开始时,它显示开始文本。当它应该停止时,它应该显示停止文本,但它仍在工作
我做错什么了吗
timer.stop();
应该停止
调度程序
,对吗?您的调度程序
实例应该是类的私有字段,因为每次调用startTime(…)
,您都在创建一个已启动但从未停止的调度程序
类的新实例。下面是一个可以做的示例:
public class YourClass : IDisposable
{
private readonly DispatcherTimer m_timer;
public YourClass()
{
m_timer = new DispatcherTimer();
m_timer.Interval = new TimeSpan(0, 0, 1);
m_timer.Tick += setTime;
}
public void Dispose()
{
m_timer.Tick -= setTime;
m_timer.Stop();
}
private void startTime(bool what)
{
if(what == false)
{
MessageBox.Show("Start");
m_timer.Start();
}
if(what == true)
{
MessageBox.Show("Stop");
m_timer.Stop();
}
}
}
我还添加了
IDisposable
实现,以确保Dispatcher
实例已正确取消订阅并停止。在方法之外定义dispatchertimer
:
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();
}
}
在当前代码中,每次调用该方法时,您都在创建一个新的dispatchertimer
实例
Class A
{
private DispatcherTimer _timer; // This is a global variable
public void StartTime(bool what)
{
DispatcherTimer timer = new Dispatcher(); //This is a local variable
...
}
}
调用StartTime函数时,计时器是一个新实例。如果运行StartTime(false)和StartTime(true),它将有两个Dispatcher 如果调用stop,您将获得多少个事件?可以尝试先停止,然后显示消息框,这样当消息框显示时它就已经停止了。仅供参考,Dispatcher和Dispatcher是不同的类,它们不可互换谢谢。。。再说一次,我必须学到很多;)你有权利。当我像你说的那样调用方法时,我总是创建新实例。谢谢!
Class A
{
private DispatcherTimer _timer; // This is a global variable
public void StartTime(bool what)
{
DispatcherTimer timer = new Dispatcher(); //This is a local variable
...
}
}