Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# thread abort exception

What happens after a thread.Abort() ??

Say i have:

Thread mWorker = new Thread(new ThreadStart(this.run));
..
mWorker.Start();

**where**

private void run() 
{
      Logger.d(TAG, "run()");

      ...
      try {
        while (this.mRunning){
          ...
        }
      } catch (ThreadAbortException tae){
           Logger.e(TAG,"some msg", tae);
           this.doSomething();
      } catch (IOException ioe){
           Logger.e(TAG,"some msg", ioe);
           this.doSomething();
      } catch (Exception e){
           Logger.e(TAG,"some msg", e);
           this.doSomething();
      } finally {
            gracefoulyClose();
      }

      Logger.d(TAG, "run() - ended");
}

Thread is more complex.. but the esential is displayed here. So what happens when Abort() gets called? will my catch work and continue with the call of doSomething()?

Because i still receive in console:

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
An exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll but was not handled in user code

But i do have a catch for that. Don't I ??

like image 521
pulancheck1988 Avatar asked Feb 20 '23 12:02

pulancheck1988


1 Answers

From the doc:

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. When this exception is raised, the runtime executes all the finally blocks before ending the thread. Because the thread can do an unbounded computation in the finally blocks or call Thread.ResetAbort to cancel the abort, there is no guarantee that the thread will ever end. If you want to wait until the aborted thread has ended, you can call the Thread.Join method. Join is a blocking call that does not return until the thread actually stops executing.

So in other words, after your catch block for the ThreadAbortException executes, the exception is re-raised, so your last logger line (e.g. Logger.d(TAG, "run() - ended")) never executes. But since the call to this.doSoemthing is in the catch block for the ThreadAbortException, it will execute.

Note also that, your finally block does execute (refer to doc above).

like image 119
dcp Avatar answered Mar 05 '23 09:03

dcp