If I need to cancel some operation on a thread, when should I use Thread.Abort
vs Thread.Interrupt
. I read the documentation on it but not sure which scneario should i use a particular call between two.
If there is any third way of doing it, please let me knwo about it too with pro and cons.
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.
Abort(Object) Obsolete. Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Calling this method usually terminates the thread.
interrupt() does not interrupt the thread, it continues to run.
Thread. Abort is a lot safer than it used to be for the following reasons. The runtime will defer aborts while execution is in unmanaged code. The abort will allow finally blocks to execute.
I would avoid using Thread.Abort
at all costs. Its behavior is much safer and predictable since .NET 2.0, but there are still some pretty serious pitfalls with it. Most of the aborts inside managed code can be made safe, but not all of them. For example, I believe there are some subtle problems if an abort request is triggered during the processing of a static constructor. Nevermind, the fact that the out-of-band exception can occur at anytime giving you little control over defining where the safe points for shutdown are located.
There are several acceptable ways to terminate a thread gracefully.
Thread.Interrupt
WaitHandle
eventsI discuss these methods in my answer here.
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