【发布时间】: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) 重载提供了保证。