Disposing System.Threading.Timer

I guess there are many ways to dispose this a timer, I was looking for an efficient way of doing it and making sure that after the Dispose method was called I had no outstanding timer notifications.

In Win32 there is the concept of timer-queue timers, and in that APi set, when a timer is deleted by using DeleteTimerQueueTimer API, if INVALID_HANDLE_VALUE is passed to the CompletionEvent, the API automatically wait for any pending notification.

So, applying the same concept, I pass an “invalid” wait handle to Timer.Dispose and it works. Here is the invalid wait handle class:

 internal sealed class InvalidWaitHandle : WaitHandle
{
    private readonly static InvalidWaitHandle instance = new InvalidWaitHandle();

    private InvalidWaitHandle() {}

    public static WaitHandle Instance {
        get {
            return instance;
        }
    }

    public override IntPtr Handle {
        get {
            return WaitHandle.InvalidHandle;
        }
        set {
            throw new InvalidOperationException();
        }
    }
}

And for disposing the Timer, just write:

 this.timer.Dispose(InvalidWaitHandle.Instance);

Comments

  • Anonymous
    January 14, 2015
    Wouldn't that be the same as calling System.Threading.Timer.Dispose()? If you don't use the wait handle, why create one? System.Threading.Timer.Dispose(WaitHandle) isn't blocking afaik, nor is System.Threading.Timer.Dispose(). I think to make sure no callbacks are queued up you create a proper WaitHandle object and wait for it to signal after calling System.Threading.Timer.Dispose(WaitHandle). Correct me if I'm wrong.