首页 > 解决方案 > 如何在 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吧?

标签: c#wpfdispatchertimer

解决方案


定义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在您当前的代码中,每次调用该方法时,您都会创建一个新实例。


推荐阅读