[英]Using TaskScheduler.UnobservedTaskException can avoid the process being killed?
[英]UnobservedTaskException is not killing the process
我试图理解.NET 4.0中的UnobservedTaskException问题,所以我编写了folloging代码
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的相同行为,可以将其添加到app.config文件中(如TaskScheduler.UnobservedTaskException事件中所述 ):
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.