When aborting the execution of a thread I’m always doubting between a graceful exit with an event handler like this:
int result = WaitHandle.WaitAny(handles); if (result = WAIT_FINALIZE) FinalizeAndExit();
and using the event to signal the thread it must terminate
or just handling the ThreadAbortException to finalize the thread…
try { // Main execution } catch(ThreadAbortException e) { // FinalizeAndExit(); } finally { }
I’m usually inclined to use the ThreadAbortException approach since it can be handled but it is re-raised at the end of the catch block, and it also avoids the thread from being kept alive by ‘treacherous’ methods, but I’ve seen both approaches.
What’s your opinion? Is there any situation where it’s best to use one over another, or is it best to use always approach x?
Generally, the first method it preferrable.
It’s hard (if not impossible) to write code that will always handle a ThreadAbortException gracefully. The exception can occur in the middle of whatever the thread happens to be doing, so some situations can be hard to handle.
For example, the exception can occur after you have created a FileStream object, but before the reference is assigned to a variable. That means that you have an object that should be disposed, but the only reference to it is lost on the stack somewhere…