tags:

views:

252

answers:

3

Let's say we have some code like this running in the separate thread:

private static void ThreadFunc() 
{
ulong counter = 0;

    while( true ) 
    {

        try 
        {
        Console.WriteLine( "{0}", counter++ );
        }
        catch( ThreadAbortException ) 
        {
        Console.WriteLine( "Abort!" );
        }

    }
}

When Thread.Abort is called, is it possible situation when exception is thrown outside of catch block?

+1  A: 

I am not 100% what you are asking but I wanted to point out that you will never be able to swallow a ThreadAbortException:

When a call is made to the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

Are you asking if it is possible to catch a ThreadAbortException that is thrown in another thread here with a try/catch? If that is your question, then no, you cannot.

Andrew Hare
+4  A: 

Actually yes, a ThreadAbortException is special. Even if you handle it, you can't stop it because it gets re-thrown at the end of the catch try/catch/finally scope. Not to mention even though there is no obvious executable code outside of your try/catch/finally, every iteration of the loop winds up outside of the scope for a small duration.

Unless you are actually doing something in the catch block, I would just make a try/finally and don't worry about ThreadAbortException. There are much better ways of aborting a thread without using Thread.Abort which is not only the thread equivalent of killing a process from the task manager, it's also not guaranteed to work because if your thread is currently calling out to some unmanaged code, the thread will not abort until control returns to managed code.

It's much better to use some type of synchronization primitive such as a ManualResetEvent to act as a flag telling your thread when to exit. You could even use a boolean field for this purpose which is what the BackgroundWorker does.

Josh Einstein
+1. Just don't Abort threads, it's pretty much never a good idea.
bobbymcr
+3  A: 

Yes. I suspect that you're asking because thread interruptions only occur when a thread could otherwise block (or if it's already blocked) - e.g. for IO.

There's no such guarantee for abort. It can happen at any time, basically, although there are delay-abort regions such as constrained execution regions and catch/finally blocks, where the abort request is just remembered, and the thread aborted when it exits the region.

Synchronous thread aborts (i.e. aborting your own thread) is reasonably safe, but asynchronous aborts (aborting a different thread) are almost always a bad idea. Read "Concurrent Programming on Windows" by Joe Duffy for further information.

Jon Skeet
Thanks, Jon. My brain just blew a circuit breaker.
Josh Einstein