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 that the exception is thrown outside of catch block?
ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread.
In C#, Thread class provides the Join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t. Join() causes the current thread to pause its execution until thread it joins completes its execution.
Actually yes, a ThreadAbortException
is special. Even if you handle it, it will be automatically re-thrown by the CLR at the end of the try/catch/finally. (As noted in the comments, it can be suppressed with ResetAbort
but by that point the code smells like rotten fish.)
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 so the abort could occur outside of your try block.
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 not only chaotically interrupts your code at an unpredictable point, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With