如何在C#WPF中停止DispatcherTimer

时间:2018-08-21 13:06:52

标签: c# wpf dispatchertimer

我正在检查时间和何时等于要停止调度程序的时间。

但是它不起作用。调用Stop()后,计时器仍在工作。

private void startTime(bool what)
{
    DispatcherTimer timer = new DispatcherTimer();

    if(what == false)
    {
        MessageBox.Show("Start");

        timer.Interval = new TimeSpan(0, 0, 1);
        timer.Tick += setTime;
        timer.Start();
    }

    if(what == true)
    {
        MessageBox.Show("Stop");

        timer.Stop();
    }
}

启动时,它会显示开始文本。当它应该停止时,它应该显示“停止”文本,但它仍在工作。

我做错了吗?

timer.stop();

应该停止Dispatcher,对吗?

3 个答案:

答案 0 :(得分:4)

在您的方法之外定义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的新实例。

答案 1 :(得分:2)

您的DispatcherTimer实例应该是您班级的私有字段,因为每次调用startTime(...)时,您都在创建DispatcherTimer类的新实例,该实例已启动但从未停止过。这是一个可以做的例子:

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实例已正确取消订阅并已停止。

答案 2 :(得分:0)

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),它将有两个DispatcherTimer;

相关问题