Is using Thread.Abort() and handling ThreadAbortException in .NET safe practice?

前端 未结 7 1021
执念已碎
执念已碎 2020-12-10 06:26

I need to develop a multithreaded Azure worker role in C# - create multiple threads, feed requests to them, each request might require some very long time to process (not my

7条回答
  •  孤街浪徒
    2020-12-10 07:07

    Thread.Abort is an unsafe way of killing the thread.

    1. It rises an asynchronous ThreadAbortException which is a special exception that can be caught, but it will automatically be raised again at the end of the catch block
    2. It can leave the state corrupted, and your application becomes unstable
    3. TAE is raised in the other thread

    The best practise is to use wrappers that support work cancellation, such as the Task class or use volatile bool. Instead of Thread.Abort consider using Thread.Join which will block the calling thread until the working thread is disposed of.

    Some links:
    - How To Stop a Thread in .NET (and Why Thread.Abort is Evil)
    - Managed code and asynchronous exception hardening
    - The dangers of Thread.Abort

提交回复
热议问题