views:

1794

answers:

3

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 reraised 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 is best to use one over another, is it best to use always approach x?

+2  A: 

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.

Dror Helper
+4  A: 

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

Guffa
On the other hand, if I don't Abort the thread I can't never really be sure the thread won't just be kept alive blocking my main execution.
Jorge Córdoba
+1. "Indeed, thread abort exceptions are pure unmitigated evil and you should never use them." -C# compiler team member Eric Lippert http://blogs.msdn.com/ericlippert/archive/2009/03/06/locks-and-exceptions-do-not-mix.aspx
Craig Stuntz
@Jorge Córdoba, you can set the background flag on the thread, then it will be killed when your application ends if you can't make it end by itself.
Guffa
+2  A: 

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.

ChrisF