0

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();
}
Fré
  • 1
  • 1
  • Do you use a debugger? Besides, your code is not meaningful at all. When do you try to stop/restart? How is this part called? Are you creating a new timer everytime? – JeffRSon Dec 27 '13 at 16:59

1 Answers1

0

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);
        }
yo chauhan
  • 12,079
  • 4
  • 39
  • 58
  • Thanks, but how can I solve the "Error, Use of unassigned local variable 'preservedDispatcherTimer' " ? It isn't working by adding new() either... – Fré Dec 27 '13 at 18:22
  • set it to null like DispatcherTimer preservedDispatcherTimer=null; – yo chauhan Dec 27 '13 at 18:36