Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 556
Ian Ringrose Avatar asked Nov 25 '10 12:11

Ian Ringrose


People also ask

Do we need to dispose timer C#?

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.

Is timer thread safe?

Timer is not thread-safe.

Does system timers timer run in a separate thread?

Timer raises the elapsed event, is it raised in an independent thread? Yes, they run in a different thread.


1 Answers

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.

like image 121
Tim Lloyd Avatar answered Oct 28 '22 22:10

Tim Lloyd