UnobservedTaskException is not killing the process

[亡魂溺海] 提交于 2019-12-10 17:28:58

问题


I am trying to understand the UnobservedTaskException issue in .NET 4.0 so I wrote the folloging code

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 is fired and then my app just keeps working. However according to MSDN the process should be killed. Can anyone tell me why ?


回答1:


If you run this code on a machine that only has .Net 4.0 installed it will indeed crash.

Since all the .Net versions since 4.0 were in-place updates even if you target your application for .Net 4.0 it will run on a later version on a machine that has one.

To get the same behavior of .Net 4.0 while running on a later version you can add this to your app.config file (as described in TaskScheduler.UnobservedTaskException Event):

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


来源:https://stackoverflow.com/questions/31894259/unobservedtaskexception-is-not-killing-the-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!