Reliably stop System.Threading.Timer?

JayPea picture JayPea · Jun 17, 2011 · Viewed 77.5k times · Source

Well I've searched a lot for a solution to this. I'm looking for a clean and simple way to prevent the callback method of a System.Threading.Timer from being invoked after I've stopped it.

I can't seem to find any, and this has led me, on occassion, to resort to the dreaded thread-thread.sleep-thread.abort combo.

Can it be done using lock?

Answer

Owen Blacker picture Owen Blacker · Jan 16, 2013

An easier solution might to be to set the Timer never to resume; the method Timer.Change can take values for dueTime and period that instruct the timer never to restart:

this.Timer.Change(Timeout.Infinite, Timeout.Infinite);

Whilst changing to use System.Timers.Timer might be a "better" solution, there are always going to be times when that's not practical; just using Timeout.Infinite should suffice.