Benefits of Thread.ResetAbort

When a thread is canceled through Thread.Abort (), a ThreadAbortException is thrown inside Thread Thread. Called. This causes the thread to immediately stop running, and the exception bubbles up to the call stack until it leaves the main thread method. This leads to interruption of the stream.

What are the benefits of the ExceptionHandler for ThreadAbortException in the main thread method in which Thread.ResetAbort () is called when the thread exits after the catch block due to exit from the main method?

private void ThreadMainMethod( ) { try { while(runningAllowed = true) { //Do some work here } } catch ( ThreadAbortException ) { Thread.ResetAbort( ); } } 
+4
source share
4 answers

Probably the only reason you will do this is if you were in an excellent position to decide if you really should stop doing it.

So maybe the stream would catch him, check the status of something, and then return to his work again. Although this implies that you mainly use " .abort() " to control the flow of this stream. And this is a good idea. You must communicate with him differently.

In general, I think that there are not many cases when this is a good idea, and this will not be advice for any specific model or implementation that I can think of.

+2
source

One scenario that I can think of is that you want to control the flow in a controlled manner. Let's say you have a workflow that polls some resource. If the main application thread calls Abort in the workflow, a ThreadAbortException is thrown. Then you can catch this exception in the start method for the workflow, call ResetAbort , and then end the method by freeing the resource, closing open files / connections and so on:

 public void ThreadStarter() { try { RunWorkerLoop(); } catch (ThreadAbortException) { Thread.ResetAbort(); } // clean up and end gracefully } 
+5
source

In your particular case, this does not really matter, because the thread will terminate after the method is started.

However, in another case, you may have a method that runs in an infinite loop. In this case, you can disable the thread using ThreadAbortException (I am not saying that you should, but you can). If a thread, for some reason, decides to continue, despite an exception, it needs to call ResetAbort to prevent ThreadAbortException from automatically recovering.

+2
source

I found that calling ResetAbort() would be very useful in this elegant WaitFor timeout implementation .

+1
source

All Articles