gpt4 book ai didi

.net - ThreadAbortException 的不良后果是什么?

转载 作者:行者123 更新时间:2023-12-01 11:44:26 26 4
gpt4 key购买 nike

我最近在遗留代码库中遇到了一种多线程模式,它依赖于 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。使用 CancellationTokenCancellationTokenSource 允许您以干净的方式设计正确的取消,并且线程可以正确处理自己的清理。

关于.net - ThreadAbortException 的不良后果是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16655114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com