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);