c# - UnobservedTaskException 没有终止进程

标签 c# .net-4.0 task-parallel-library task unobserved-exception

我试图了解 .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> 

关于c# - UnobservedTaskException 没有终止进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31894259/

相关文章:

c# - 从 32 位进程中检索 x64 程序文件路径

c# - 输入字符串在 double.Parse 中的格式不正确

c# - 在 WPF 中对 Icollectionview 进行排序和分组

c# - 是否可以在面向 4.0 的项目中引用面向 .net 4.5 的程序集?

c# - async/await中的return语句在哪里

c# - 如何更改整个项目的命名空间?

.net - SendKeys.Send NullReferenceException 异常

c# - 如何在 C# 中初始化一个 BigInteger?

c# - ConstructorInfo.GetParameters 是线程安全的吗?

c# - 异步任务中出现大量 ping - 出现异常 "An asynchronous call is already in progress."