我有一个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()...
https://msdn.microsoft.com/zh-cn/library/system.timers.timer.stop(v=vs.110).aspx有一个代码示例,显示如何避免此确切问题。 – paxdiablo
您真的*想要确保Elapsed事件不会再次运行。你不能在你的事件处理程序中得到这样的保证,[你必须检查](http://stackoverflow.com/a/4810724/17034)。不要考虑System.Threading.Timer,它的Dispose(WaitHandle)重载提供了保证。 –