Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadAbortException

Tags:

c#

.net

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?

like image 612
Overdose Avatar asked Dec 06 '09 19:12

Overdose


People also ask

What is ThreadAbortException?

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.

What does thread join Do C#?

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.


1 Answers

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.

like image 87
Josh Avatar answered Sep 24 '22 23:09

Josh