Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with using Thread.Abort()

So I know that you shouldn't use

Thread.Abort() 

But I've never been given a good explanation. Is there a performance penalty or some hidden gotcha?

I know you can't ignore/swallow the ThreadAbortException (which makes sense)

like image 826
Jan Bannister Avatar asked Oct 13 '09 10:10

Jan Bannister


People also ask

Is thread Abort safe?

Use the Thread. Abort method with caution. Particularly when you call it to abort a thread other than the current thread, you don't know what code has executed or failed to execute when the ThreadAbortException is thrown.

Which is the exception thrown when a thread is aborted?

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

What is the difference between thread interrupt and thread Abort?

Abort method throws a ThreadAbortException, the Thread. Interrupt method throws a ThreadInterruptException. Essentially, a call to the Thread. Interrupt method interrupts the thread and throws a ThreadInterruptedException to interrupt the thread inside of a blocking call.


1 Answers

In addition to all of the other good answers here, let me add that there is no guarantee whatsoever that a call to Thread.Abort will actually abort the thread in question, ever. It is possible (though not particularly easy) to "harden" a thread against being aborted. If, for example, you are aborting a thread because you believe it to be running hostile code then the hostile code could be resisting its own destruction.

If you have a long-running operation involving code that you do not own that must be taken down cleanly, the correct way to do this is to put that code in its own process, not its own thread. (And preferably in a highly security-restricted appdomain in that process.) You can then cleanly kill the process.

In short, Thread.Abort is at best indicative of bad design, possibly unreliable, and extremely dangerous. It should be avoided at all costs; the only time you should ever even consider aborting a thread is in some sort of "emergency shutdown" code where you are attempting to tear down an appdomain as cleanly as possible.

like image 60
Eric Lippert Avatar answered Oct 13 '22 12:10

Eric Lippert