我正在阅读一本关于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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
这本书说:
当您的线程完成处理中止异常时,运行时会在异常处理程序的末尾隐式重新抛出它.就像你自己重新抛出异常一样.因此,任何外部异常处理程序或finally块仍将正常执行.在该示例中,对Join的调用将不会像最初预期的那样永远等待.
所以我围绕Thread.Abort()调用包装一个try catch并设置一个断点,期望它达到这个,考虑到文本说"任何外部异常处理程序或最后块仍将正常执行".但它没有.我绞尽脑汁想弄清楚原因.
任何人都有任何想法为什么不是这种情况?这本书错了吗?
提前致谢.
在被中止的线程上抛出异常.一旦抛出异常就会向该线程的调用堆栈移动,但它不会跳转到另一个线程,也不会跳转到调用者Thread.Abort.
索赔是:
因此,任何外部异常处理程序或finally块仍将正常执行.
对此声明的更好测试是以下代码:
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?");
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果ThreadAbortException是正常类型的例外,我们不会期望达到这条线"Do we get here?",但我们确实如此.