How to stop System.Threading.Timer in callback method

30,772

Solution 1

First, the callback method must have the timer instance in-scope.

Then the simple incantation

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

will shut down the timer. It is possible that the timer might invoke the callback method once more after the change, I believe, depending on the state it's in.

Solution 2

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

Solution 3

Try this:

If you want you could let timer continue firing the callback method and include the code below

private void CreatorLoop(object state)  
 { 
   if (Monitor.TryEnter(lockObject) 
   { 
     try 
     { 
       // Work here 
     } 
     finally 
     { 
       Monitor.Exit(lockObject); 
     } 
   } 
 } 

check out this link too:

Stopping timer in its callback method

Solution 4

You can simply call myTimer.Change(Timeout.Infinite, Timeout.Infinite).

Technically, only the first parameter (dueTime) needs to be specified as Timeout.Infinite for the timer to stop.

For more information, see Timer.Change Method.

Solution 5

I found out the hard way that Change(Timeout.Infinite, Timeout.Infinite) isn't quite reliable, and switched over to System.Timers.Timer with AutoReset = false.

Share:
30,772
Proceso
Author by

Proceso

Updated on June 17, 2020

Comments

  • Proceso
    Proceso almost 4 years

    How can I stop System.Threading.Timer in it's call back method. I referenced MSDN, but couldn't find anything useful. Please help.

  • usr
    usr almost 12 years
    It's better to dispose it because that captures the semantic meaning better. It might also be faster.
  • usr
    usr almost 12 years
    It's better to dispose it because that captures the semantic meaning better. It might also be faster.
  • Nicholas Carey
    Nicholas Carey almost 12 years
    Depends on whether the timer is to be restarted later or you're done with it. The OP specified that she wanted to "stop the timer", not "destroy the timer". The timer instance and its lifetime is the responsibility of its creator.
  • Jon Senchyna
    Jon Senchyna almost 12 years
    It depends on if the user is permanently stopping the timer, or if they're just pausing it for a time and possibly restarting it at a later time. If you use .Dispose() to simply pause the timer, you will run into issues if you want to either restart it, or simply change the dueTime or period. In those cases, it's safer (and easier) to just use timer.Change().
  • Volma
    Volma almost 12 years
    what if I want to restart it later?
  • Proceso
    Proceso almost 12 years
    yap with that solution that's the problem, thread doesn't stop immediately.