Search code examples
c#multithreadingcancellationthread-abort

Thread.Abort vs Thread.Interrupt


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 scenario should I use a particular call between two.

If there is any third way of doing it, please let me know about it too with pros and cons.


Solution

  • 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.