When you dispose a “raw” .net timer, you can pass in a wait handle to be called once the Win32 timer has been destroyed and you can them assume that your call back will not be called. (And the timer will be considered "dead" by the GC)
How do I do this with a System.Timers.Timer?
Best practices when working in C# say that you should clean up your resources if the class implements IDisposable interface. There are two ways to dispose the Timer: Dispose the timer by calling the Dispose() method inside a try/catch block to avoid exception.
Timer is not thread-safe.
Timer raises the elapsed event, is it raised in an independent thread? Yes, they run in a different thread.
Set a flag before you call dispose, and check this flag in your elapsed handler. Even if the timer does fire, the flag will prevent any associated handler code from being run. You could formalize this pattern by writing a wrapper for the timer.
Make sure your flag is marked as volatile as it will be accessed from different threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With