Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for System.Threading.Timer Callbacks to Complete before Exiting Program

I have a List<System.Threading.Timer>. Each Timer fires at a configurable interval (default 10 minutes). All call the same callback method (with a different parameter). The callback method can take several seconds to complete it's work.

When the program terminates, it looks like execution of the callback method is immediately halted (am I seeing that correctly?).

How can I elegantly wait for any currently-executing callback methods to complete before exiting the program?

like image 955
Eric J. Avatar asked Jan 30 '12 09:01

Eric J.


1 Answers

You can Dispose all timers with WaitHandler parameter. This handler will be signaled only when callback method is completed (as spec says: "The timer is not disposed until all currently queued callbacks have completed.")

void WaitUntilCompleted(List<Timer> myTimers)
{
    List<WaitHandle> waitHnd = new List<WaitHandle>();
    foreach (var timer in myTimers)
    {
        WaitHandle h = new AutoResetEvent(false);
        if(!timer.Dispose(h)) throw new Exception("Timer already disposed.");
        waitHnd.Add(h);
    }
    WaitHandle.WaitAll(waitHnd.ToArray());
}

Edit: @Peter underlined importance of the Dispose method return value. It returns false when timer already disposed. To make sure this solutions stays reliable, I modified it to throw exception when Timer already disposed as we can't control in such case when its callback finishes, despite earlier disposal callback might still be running!

like image 121
Tomek Avatar answered Oct 06 '22 01:10

Tomek