Reputation: 751
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?
Upvotes: 7
Views: 6008
Reputation: 133975
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.
Upvotes: 4
Reputation: 17808
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.
Upvotes: 14