0

每次不满足条件时,我都希望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();
}
4

1 回答 1

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);
        }
于 2013-12-27T17:03:54.530 回答