C# .Net:如何等待System.Timers.Timer停止

C# .Net:如何等待System.Timers.Timer停止,c#,.net,timer,C#,.net,Timer,我在主线程中创建了一个System.Timers.Timer实例。现在我调用timer.Stop()尝试终止该时间,并希望等待计时器真正终止。我怎么能这么做 是否有类似的方法,如System.Threading.Thread.Join() 这里有一些代码 //the main thread: var aTimer = New Timer(); aTimer.Elapsed += SomeTimerTask; aTimer.AutoReset = True; aTimer.Start(); //

我在主线程中创建了一个
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()...

当您调用stop时,计时器不会启动已运行的
,因为您可以在
stop()
-方法中读取:

通过将Enabled设置为false,停止引发已用事件

只有当
定时器
s
启用
-属性设置为
且给定的
间隔(必须设置)已过时(这可能会发生多次),才会触发已过-事件


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

可以使用ResetEvents,它是等待句柄,可以阻止线程,直到将状态设置为signaled:

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();
    }
}
如果您想要一个异步/基于任务的解决方案,您必须使用方法

,该方法有一个代码示例,说明如何避免这个问题。您真正想要的是确保事件不会再次运行。在事件处理程序中,您无法得到这样的保证。考虑系统,线程。定时器代替,它的处置(WaitHandle)过载提供了保证。