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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With