2016-06-28 103 views
1

我有一个System.Timers.Timer实例在主线程中创建。现在我打电话timer.Stop()试图终止这段时间,并希望等到定时器真正终止。我怎么能这样做?.net:如何等待,直到System.Timers.Timer停止

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

这里有一些代码,当你调用停止,你可以在Stop() - 方法的docs

//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()... 
+0

https://msdn.microsoft.com/zh-cn/library/system.timers.timer.stop(v=vs.110).aspx有一个代码示例,显示如何避免此确切问题。 – paxdiablo

+0

您真的*想要确保Elapsed事件不会再次运行。你不能在你的事件处理程序中得到这样的保证,[你必须检查](http://stackoverflow.com/a/4810724/17034)。不要考虑System.Threading.Timer,它的Dispose(WaitHandle)重载提供了保证。 –

回答

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方法

0

定时器不火起来的Elapsed

停止升起的消逝事件设置为启用为false。

消逝 - 活动时Timer小号Enabled,物业设置为true和给定Interval(你必须设置)已过去(这可以发生多次)时才会触发。

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