I have a System.Threading.Timer
that will be toggled on and off. I know of two methods to turn off the timer:
Timer.Change(-1,-1)
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?
Currently, the only way to stop a Threading Timer is by calling Change(Timeout. Infinite, Timeout.
Timers. Timer is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject property, whereas System. Threading.
Timers. Timer raises the elapsed event, is it raised in an independent thread? Yes, they run in a different thread. The System.
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)
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.
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