.net之ThreadAbortException 的不良后果是什么
我最近在遗留代码库中遇到了一种多线程模式,它依赖于 Thread.Abort()
方法来取消对外部系统的同时请求。一个不好的后果是很难将超时异常与其他异常类型区分开来。
在多线程控制流中不使用 ThreadAbortException
的其他原因是什么?
请您参考如下方法:
What are the other reasons not to use ThreadAbortExceptions in multithreaded control flow?
Thread.Abort 会使线程处于非常奇怪的状态,这可能无法干净地处理。
来自 Thread.Abort 的文档:
if one thread calls Abort on another thread, the abort interrupts whatever code is running. There is also a chance that a static constructor could be aborted. In rare cases, this might prevent instances of that class from being created in that application domain. In the .NET Framework versions 1.0 and 1.1, there is a chance the thread could abort while a finally block is running, in which case the finally block is aborted.
如果您在多线程代码中工作,这可能会更加危险,因为它可能会触发死锁。这也记录在案:
The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.
一般来说,使用框架的 cooperative cancellation model 更安全、更简洁。 ,永远不要调用 Thread.Abort
。使用 CancellationToken
和 CancellationTokenSource
允许您以干净的方式设计正确的取消,并且线程可以正确处理自己的清理。
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。