【问题标题】:.Net: how to wait until System.Timers.Timer stops.Net:如何等到 System.Timers.Timer 停止
【发布时间】:2016-06-28 06:17:02
【问题描述】:

我在主线程中创建了一个System.Timers.Timer 实例。现在我打电话给timer.Stop() 试图终止那个时间,并想等到计时器真正终止。我怎么能这样做?

有没有类似System.Threading.Thread.Join()的方法?

这里有一些代码

//the main thread:
var aTimer = New Timer();
aTimer.Elapsed += SomeTimerTask;
aTimer.AutoReset = True;
aTimer.Start();

//some other logic...

//stop that timer:
aTimer.Stop();

//now I need to wait until that timer is really stopped,
//but I cannot touch the method SomeTimerTask().
//so I need something like System.Threading.Thread.Join()...

【问题讨论】:

  • msdn.microsoft.com/en-us/library/… 有一个代码示例,展示了如何避免这个确切的问题。
  • 真正想要确保 Elapsed 事件不会再次运行。你不能在你的事件处理程序中得到这样的保证,you'll have to check。请考虑使用 System.Threading.Timer,它的 Dispose(WaitHandle) 重载提供了保证。

标签: c# .net timer


【解决方案1】:

您可以使用 ResetEvents,它是等待句柄,可以阻塞线程,直到您将状态设置为已发出信号:

class TimerAndWait
{
    private ManualResetEvent resetEvent = new ManualResetEvent(false);

    public void DoWork()
    {
        var aTimer = new System.Timers.Timer(5000);
        aTimer.Elapsed += SomeTimerTask;
        aTimer.Elapsed += ATimer_Elapsed;
        aTimer.AutoReset = true;
        aTimer.Start();

        // Do something else

        resetEvent.WaitOne(); // This blocks the thread until resetEvent is set
        resetEvent.Close();
        aTimer.Stop();
    }

    private void ATimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        resetEvent.Set();
    }
}

如果你想要一个基于异步/任务的解决方案,你必须使用ThreadPool.RegisterWaitForSingleObject 方法

【讨论】:

    【解决方案2】:

    当您调用 stop 时,计时器不会触发 Elapsed,因为您可以在 Stop() 方法的 docs 中看到:

    通过将 Enabled 设置为 false 来停止引发 Elapsed 事件。

    Elapsed-事件仅在 Timers Enabled-Property 设置为 true 并且给定的 Interval(您必须设置)已过去时触发(这可能会发生多次)。

    因此,如果您在间隔结束之前停止计时器,您可能需要以其他方式触发您的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多