Question

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?

Was it helpful?

Solution

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...

OTHER TIPS

If I can I try to avoid using Thread.Abort. The problem with Thread.Abort is that it could happen in (almost) any line of the executing code and might cause some "interesting" behavior (read: bugs). Intead I prefer to have a point of exit on my code that checks for an event or variable to see if it the thread should stop running and gracefully exit.

Surely if the termination event is expected then it's not an exception (by the strict definition of the term) so therefore you should be using the first method. A graceful exit also shows that you are in control.

While exceptions are useful and in some cases necessary, they can and do get overused.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top