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?
source share