WPF Dispatchertimer is not stopping, nor restarting

1.7k Views Asked by At

I want a DispatcherTimer to restart everytime the conditions are not met. Only when the if-condition is met for 5 seconds, the method can continue.

How should I stop the Dispatchertimer? The timeToWait variable is set to 3000, that works as intended.

Below is the code in C#. It is not responding as I want. It only starts, but never stops or restarts. I am making a WPF application.

dispatcherTimerStart = new DispatcherTimer();

    if (average >= centerOfPlayingField - marginOfDetection && average <= centerOfPlayingField + marginOfDetection)
    {
      dispatcherTimerStart.Interval = TimeSpan.FromMilliseconds(timeToWait);
      dispatcherTimerStart.Tick += new EventHandler(tick_TimerStart);
      startTime = DateTime.Now;
      dispatcherTimerStart.Start();
    } else
    {
      dispatcherTimerStart.Stop();
      dispatcherTimerStart.Interval = TimeSpan.FromMilliseconds(timeToWait);
    }


private void tick_TimerStart(object sender, EventArgs args)
{
  DispatcherTimer thisTimer = (DispatcherTimer) sender;
  thisTimer.Stop();
}
1

There are 1 best solutions below

2
On

you need to preserve the dispatcherTimer that enter your if block because in your else block you are stopping the new instance of DispatcherTimer not the one that entered the if block.

take a class level field

DispatcherTimer preservedDispatcherTimer=null;



var dispatcherTimerStart = new DispatcherTimer();

        if (average >= centerOfPlayingField - marginOfDetection && average <= centerOfPlayingField + marginOfDetection)
        {
            **preservedDispatcherTimer = dispatcherTimerStart;**
            dispatcherTimerStart.Interval = TimeSpan.FromMilliseconds(timeToWait);
            dispatcherTimerStart.Tick += new EventHandler(tick_TimerStart);
            startTime = DateTime.Now;
            dispatcherTimerStart.Start();
        }
        //use preservedDispatcherTimer in else 

        else if(preservedDispatcherTimer!=null)
        {
            preservedDispatcherTimer.Stop();
            preservedDispatcherTimer.Interval = TimeSpan.FromMilliseconds(timeToWait);
        }