Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Abort vs Thread.Interrupt

Tags:

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.

like image 878
Silverlight Student Avatar asked May 10 '11 13:05

Silverlight Student


People also ask

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.

What is thread abort?

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.

Does thread interrupt terminate a thread?

interrupt() does not interrupt the thread, it continues to run.

Is abort thread safe?

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.


1 Answers

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.

  • Use Thread.Interrupt
  • Poll a stopping flag
  • Use WaitHandle events
  • Specialized API calls

I discuss these methods in my answer here.

like image 51
Brian Gideon Avatar answered Nov 17 '22 01:11

Brian Gideon