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

前端 未结 7 1013
执念已碎
执念已碎 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:26

    It's very difficult to handle the TheadAbortException correctly, because it can be thrown in the middle of whatever code the thread is executing.

    Most code is written with the assumption that some actions, for example int i = 0; never causes an exception, so the critical exception handling is only applied to code that actually can cause an exception by itself. When you abort a thread, the exception can come in code that is not prepared to handle it.

    The best practice is to tell the thread to end by itself. Create a class for the method that is running the thread, and put a boolean variable in it. Both the code that started the thread and the method running the thread can access the variable, so you can just switch it to tell the thread to end. The code in the thread of course have to check the value periodically.

提交回复
热议问题