问题描述:

I have a System.Timers.Timer instance created in the main thread. Now I call timer.Stop() to try to terminate that time and want to wait until the timer is really terminated. How could I do that?

Is there any similar method like System.Threading.Thread.Join()?

Here are some codes

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

网友答案:

You could make use of a ResetEvents which are wait handles which can block a thread until you set the state to 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();
    }
}

If you want a async/task-based solution you have to use the ThreadPool.RegisterWaitForSingleObject method

网友答案:

The Timer does not fire up the Elapsed when you call stop as you can read in the docs of the Stop()-Method:

Stops raising the Elapsed event by setting Enabled to false.

The Elapsed-Event is only triggered when the Timers Enabled-Property is set to true and the given Interval (which you have to set) is elapsed (this can happen multiple times).

So if you stop your Timer before the Interval is elapsed, you might have to trigger your code in some other way.

相关阅读:
Top