Search code examples
c#wpfdispatchertimer

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?


Solution

  • 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.