randomuser
randomuser

Reputation: 109

UnobservedTaskException is not killing the process

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 ?

Upvotes: 4

Views: 222

Answers (1)

i3arnon
i3arnon

Reputation: 116548

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> 

Upvotes: 4

Related Questions