Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I stop a System.Threading.Timer

I have an application that uses timers to occasionally run monitoring tasks on secondary threads. Some of these cleanup tasks take a lot of time and I would like to be able to abort these tasks (gracefully if possible) when my user ends the program.

Is there any way to abort the thread programatically as I can with Thread.Abort(), or would I have to add a flag to the code to indicate that the thread has finished and check for that in valrious places in the code that is started by the timer?

like image 772
Jeff Hornby Avatar asked Nov 29 '11 19:11

Jeff Hornby


2 Answers

You can stop the timer before it's callback executes using .change, but once the callback starts executing you should use an application level flag to allow your code to exit.

As a side note, you shouldn't use thread.abort() unless you are absolutely 100% sure that you know the state it is going to be left in. it can seriously destabilize your application in strange ways.

like image 126
Bradley Uffner Avatar answered Oct 12 '22 16:10

Bradley Uffner


There is no way to know the Thread on which a Threading.Timer callback will run ahead of time. Hence there is no general way to abort it. It is possible to have the callback itself communicate the Thread instance but it opens up a couple of race conditions

Note: In general using Abort is a bad practice. It's a fairly reliable way to end up with hard to detect deadlocks and / or resource leaks. It's much better to use a passive mechanism like CancellationToken

like image 39
JaredPar Avatar answered Oct 12 '22 15:10

JaredPar