WPF Dispatchertimer不会停止,也不会重新启动

时间:2013-12-27 16:54:10

标签: c# wpf dispatchertimer

我希望每次不满足条件时都重新启动 DispatcherTimer 。只有当if条件满足5秒时,该方法才能继续。

我应该如何停止 Dispatchertimer timeToWait 变量设置为3000,按预期工作。

以下是C#中的代码。它没有按我的意愿做出回应。它只会启动,但永远不会停止或重新启动。我正在制作一个WPF应用程序。

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 个答案:

答案 0 :(得分:0)

你需要保留输入if块的dispatcherTimer,因为在你的else块中你停止了DispatcherTimer的新实例,而不是那个进入if块的实例。

  

采取课程级别字段

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