gpt4 book ai didi

c# - 捕获 ThreadAbortException 时隐藏的 Throw 有什么用?

转载 作者:太空狗 更新时间:2023-10-29 20:08:53 27 4
gpt4 key购买 nike

我正在阅读一本通用 C# 开发的书,我来到了线程中止部分。

这本书说的是当你在另一个线程上调用 Thread.Abort() 时,该线程将抛出 ThreadAbortException,即使你试图抑制它它也会自动重新抛出它,除非你做了一些 bs 那是一般不屑一顾。这是提供的简单示例。

using System;
using System.Threading;

public class EntryPoint
{
private static void ThreadFunc()
{
ulong counter = 0;
while (true)
{
try
{
Console.WriteLine("{0}", counter++);
}
catch (ThreadAbortException)
{
// Attempt to swallow the exception and continue.
Console.WriteLine("Abort!");
}
}
}

static void Main()
{
try
{
Thread newThread = new Thread(new ThreadStart(EntryPoint.ThreadFunc));
newThread.Start();
Thread.Sleep(2000);

// Abort the thread.
newThread.Abort();

// Wait for thread to finish.
newThread.Join();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}

书上说:

当您的线程完成处理中止异常时,运行时会在异常处理程序结束时隐式地重新抛出它。这就像您自己重新抛出异常一样。因此,任何外部异常处理程序或 finally block 仍将正常执行。在示例中,对 Join 的调用不会像最初预期的那样永远等待。

所以我在 Thread.Abort() 调用周围设置了一个 try catch 并设置了一个断点,希望它能命中此点,考虑到文本中说“任何外部异常处理程序或 finally block 仍将正常执行”。但事实并非如此。我正在绞尽脑汁想找出原因。

有人想知道为什么不是这样吗?书错了吗?

提前致谢。

最佳答案

在中止的线程上抛出异常。一旦抛出异常,就会沿着该线程的调用堆栈向上移动,但它不会跳转到另一个线程,也不会跳转到 Thread.Abort 的调用者。

声明是:

Therefore, any outer exception handlers or finally blocks will still execute normally.

下面的代码更好地验证了这一说法:

private static void ThreadFunc()
{
ulong counter = 0;
while (true)
{
try
{
try
{
Console.WriteLine("{0}", counter++);
}
catch (ThreadAbortException)
{
// Attempt to swallow the exception and continue.
Console.WriteLine("Abort!");
}
}
catch (ThreadAbortException)
{
Console.WriteLine("Do we get here?");
}
}
}

如果 ThreadAbortException 是一种正常类型的异常,我们不希望遇到 “Do we get here?” 这行,但我们确实做到了。

关于c# - 捕获 ThreadAbortException 时隐藏的 Throw 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2830389/

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