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