Console application is not reset with an unhandled task exception

I am trying to understand why my console application does not crash due to an unhandled task exception. All I do is create a task in which I immediately throw an exception. Finally, I force GC. In the first example, I have a handler for the TaskScheduler.UnobservedTaskException event, and I see how the exception is handled.

  static async Task ThrowsException() { Console.WriteLine("Throwing!"); throw new Exception("Test exception"); } static void Main(string[] args) { TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; ThrowsException(); Console.WriteLine("Collecting garbage."); GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("Done collecting garbage."); Console.ReadKey(); } static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { Console.WriteLine("Unobserved task exception occured in finalizer."); Console.WriteLine(e.Exception.InnerException.Message); } 

Output:

 Throwing! Collecting garbage. Unobserved task exception occured in finalizer. Test exception Done collecting garbage. 

But if I comment on the line TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException , the program will still be terminated. In this case, the output is:

 Throwing! Collecting garbage. Done collecting garbage. 

Why does the application not work in this case?

+5
source share
2 answers

Not a program crash from an invisible task exception - this is a change made for .NET 4.5, see the MSDN notes section for the event . If you want your program to behave in .NET.NET 4.5 and cause it to crash, you need to add your app.config

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

This will return the previous behavior.

+4
source

ThrowsException is an async method, so if you do not wait for this method, the exception will be swallowed.
I assume that you need to call this method as follows:

 ThrowsException.Wait(); 

Or even catch the exception:

 try { ThrowsException().Wait(); } catch (AggregateException e) { // Do something } 

In addition, by reading the following, you will understand why your application did not work: TaskScheduler.UnobservedTaskException event .

0
source

All Articles