The best way to disable System.Threading.Timer

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

  • Call Timer.Change(-1,-1)
  • Dispose of the timer and create a new one if necessary

Which one is better in terms of resources and performance? Does Change(-1,-1) cause a CPU heater? Should I create a timer?

+4
source share
2 answers

Setting the initial value of the timer and interval -1 (i.e. Change(-1, -1) ) is not a β€œCPU heater”. Timers do not use CPU resources. The callback method, of course, but only during the (usually short) time that it is executed.

In any case, you should not create a new timer at all and do not disable it with Change(-1, -1) . Use the technique that best suits your model.

+4
source

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

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

To resume the change, it reverts to the normal working interval:

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

You do not need to delete and recreate it each time, and setting the interval to infinity will not waste time and additional processor cycles.

In this example, the value of this.RestartTimeout indicates how long until the first β€œtick” of the timer this.RestartTimeout after resuming, I usually use 0.

In my specific use, I usually switch the time and period of the timer, and then stop the timer as the first line of its callback, do the timer work, and then resume it at the end. This is to prevent re-entry to the long code.

(Timeout.Infite - -1)

+6
source

Source: https://habr.com/ru/post/1496905/


All Articles