gpt4 book ai didi

c# - 重温 Thread.Abort() - 它安全吗?

转载 作者:太空狗 更新时间:2023-10-29 21:36:02 28 4
gpt4 key购买 nike

关于迁移遗留多线程应用程序的 MSDN(来自 this 关于线程异常处理的页面):

In general, the change will expose previously unrecognized programming problems so that they can be fixed. In some cases, however, programmers might have taken advantage of the runtime backstop, for example to terminate threads. Depending on the situation, they should consider one of the following migration strategies:

Restructure the code so the thread exits gracefully when a signal is received.

Use the Thread.Abort method to abort the thread.

If a thread must to be stopped so that process termination can proceed, make the thread a background thread so that it is automatically terminated on process exit.

In all cases, the strategy should follow the design guidelines for exceptions. See Design Guidelines for Exceptions.

这表明使用 Thread.Abort 是终止线程的合适方法。在我不注意的时候发生了什么变化吗?我最后听到的是这可能会导致意外行为,因此不应使用。

最佳答案

Thread.Abort 比以前更安全,原因如下。

  • 当在非托管代码中执行时,运行时将推迟中止。
  • 中止将允许执行 finally block 。

但是,ThreadAbortException 何时被注入(inject)仍然存在问题。考虑这段代码。

public class Example
{
private DateTime value = DateTime.MinValue;

public void DoSomething()
{
try
{
value = DateTime.UtcNow;
}
finally
{
}
}
}

如果此代码在 32 位平台上运行,如果调用 Thread.Abort 并且 ThreadAbortException 变量可能会损坏 value在写入 value 的过程中被注入(inject)。由于 DateTime 是 8 个字节,因此必须使用多个指令进行写入。

可以通过将关键代码放在 finally block 中并使用 Constrained Execution Regions 来防止这种情况发生。 ,但是除了您定义的最简单的类型之外,要使所有类型都正确是非常困难的。即便如此,您也不能将所有内容 都放在finally block 中。

关于c# - 重温 Thread.Abort() - 它安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7081038/

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