Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to disable a System.Threading.Timer

Tags:

.net

timer

I have a System.Threading.Timer that will be toggled on and off. I know of two methods to turn off the timer:

  1. Call Timer.Change(-1,-1)
  2. Dispose the timer, and create a new one when needed

Which one is better, in terms of resources and performance? Is calling Change(-1,-1) a CPU heater? Is it expensive to create a timer?

like image 679
RoadBump Avatar asked Aug 13 '13 20:08

RoadBump


People also ask

How do you stop a timer thread?

Currently, the only way to stop a Threading Timer is by calling Change(Timeout. Infinite, Timeout.

Is System timers timer thread-safe?

Timers. Timer is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject property, whereas System. Threading.

Does System timers timer run in a separate thread?

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


2 Answers

Set the due time and period of the timer to infinite to stop operations temporarily.

MyTimer.Change(Timeout.Infinite, Timeout.Infinite);

To resume change it back to normal operation interval:

MyTimer.Change(this.RestartTimeout, this.OperationInterval);

It is not necessary to dispose and recreate it each time, and setting the interval to infinite will not waste and extra cpu cycles.

In this example the value this.RestartTimeout denotes how long until the first "tick" of the timer is ran after resuming, I use 0 normally.

In my specific use, I normally switch the due time and period of the timer, then stop the timer as the first line of it's callback, do the timer work, then resume it at the end. This is to prevent reentrance on long running code.

(Timeout.Infite is -1)

like image 168
asawyer Avatar answered Nov 25 '22 01:11

asawyer


Setting a timer's initial value and interval to -1 (i.e. Change(-1, -1)) is not a "CPU heater." Timers don't use CPU resources. The callback method does, of course, but only during the (usually brief) time when it's executing.

In any case, it is not at all expensive to create a new timer, nor will disabling it with Change(-1, -1) have any negative performance consequences. Use whichever technique best fits your model.

like image 25
Jim Mischel Avatar answered Nov 25 '22 00:11

Jim Mischel