How to stop System.Threading.Timer in callback method
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.
Proceso
Updated on June 17, 2020Comments
-
Proceso almost 4 years
How can I stop
System.Threading.Timer
in it's call back method. I referencedMSDN
, but couldn't find anything useful. Please help. -
usr almost 12 yearsIt's better to dispose it because that captures the semantic meaning better. It might also be faster.
-
usr almost 12 yearsIt's better to dispose it because that captures the semantic meaning better. It might also be faster.
-
Nicholas Carey almost 12 yearsDepends 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 almost 12 yearsIt 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 usetimer.Change()
. -
Volma almost 12 yearswhat if I want to restart it later?
-
Proceso almost 12 yearsyap with that solution that's the problem, thread doesn't stop immediately.