Environment:
Let’s say I have a main application that:
- Listen for requests for tasks to do,
- Perform those tasks (that use some resources (in a physical meaning)) one after another,
- Must be able to instantly stop a pending task to dispose the resources.
I got two timers:
- On the
timer1tick, the application is retrieving new requests and store them in aQueue, - On the
timer2tick, the application is dequeueing a request to perform the task in a newThread.
When a user ask to stop all tasks to have the resources free, I plan to simply kill the thread running the current task with Thread.Abort().
Problem:
I would like to be able to save some last configuration when killing the thread from the thread class.
Question:
Is there a way to detect when the thread is killed, like a Thread.OnAborting() event?
Or maybe could I catch the ThreadAbortException raised when calling the Thread.Abort() method? (if so, I don’t really know how to do it, could you provide some code example?)
Other than catching the
ThreadAbortExceptionno other mechanism exists. Of course, you really do not want to be callingThread.Abortanyway because theThreadAbortExceptiongets injected asynchronously and those injections points can be unpredictable. For example, it could be in the middle of a write which might leave the entire AppDomain in a corrupted state. .NET 2.0 added constrained execution regions which makes dealing with thread aborts a lot safer and easier to handle, but it is still incredibly difficult to author a block of code that can guarantee that the AppDomain will not get corrupted. My advice is to punt on theThread.Abortidea.Instead what you want to do is send a signal to the thread and allow it terminate gracefully on its own. This can be done with the following mechanisms.
Thread.InterruptYou can see my answer here for more information.