Alex Rivera | Logout

How do I safely dispose a System.Timers.Timer?

Asked 2010-11-25T12:26:40.853
10

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?

Edit
Report

1 Answer

3

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.

answered 2010-11-25T16:52:02.970

Your Answer