简体   繁体   中英

How to stop DispatcherTimer in c# WPF

I am checking the time and when is equal to something I want to stop the dispatcher.

But it doesn't work. Timer is still working after calling 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();
    }
}

When it starts, it is showing the Start text. When it should stop, it should show the Stop text but it is still working.

Did I do something wrong?

timer.stop();

Should stop the Dispatcher , right?

Define the DispacherTimer outside your method:

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();
    }
}

In your current code, you are creating a new instance of the DispacherTimer each time the method is called.

Your instance of DispatcherTimer should be a private field of your class because everytime you are calling startTime(...) , you are creating a new instance of the DispatcherTimer class that is started but never stopped. Here is an example of what could be done:

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();
        }
    }
}

I also added the IDisposable implementation to make sure the Dispatcher instance is properly unsubscribed from and stopped.

Class A
{
  private DispatcherTimer _timer; // This is a global variable
  public void StartTime(bool what)
  {
   DispatcherTimer timer = new Dispatcher(); //This is a local variable
   ...
  }
}

When you call the StartTime function,the timer is a new instance. If you run StartTime(false) and StartTime(true), it will have two DispatcherTimer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM