UnobservedTaskException 没有终止进程

UnobservedTaskException is not killing the process

我试图了解 .NET 4.0 中的 UnobservedTaskException 问题,所以我编写了以下代码

TaskScheduler.UnobservedTaskException += (sender, eventArgs) => Console.WriteLine("unobserved");

Task.Factory.StartNew(() => { throw new Exception(); }, TaskCreationOptions.LongRunning);
using (var autoResetEvent = new AutoResetEvent(false))
{
    autoResetEvent.WaitOne(TimeSpan.FromSeconds(10));
}
Console.WriteLine("Collecting");
GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine("Still working ");
Console.ReadKey();
Console.WriteLine("Still working ");
Console.WriteLine("Still working ");
Console.ReadKey();

UnobservedTaskException 被触发,然后我的应用程序继续工作。但是根据 MSDN 应该终止进程。谁能告诉我为什么?

如果你运行在一台只安装了 .Net 4.0 的机器上运行这段代码,它确实会崩溃。

因为自 4.0 以来的所有 .Net 版本都是就地更新,即使您将您的应用程序定位到 .Net 4.0,它也会 运行 在具有 .Net 4.0 的机器上的更高版本上。

要在 运行 更高版本上获得与 .Net 4.0 相同的行为,您可以将其添加到 app.config 文件中(如 TaskScheduler.UnobservedTaskException Event 中所述):

<runtime> 
    <ThrowUnobservedTaskExceptions enabled="true"/> 
</runtime>