I have the below test program which sets up the UnobservedTaskException however the OnTaskException method is never executed. Any ideas?
NOTE:
If I remove the "for loop" then everything works as expected.
static void Main()
{
SetupUnobservedTaskExceptionHandling();
Task.Factory.StartNew(() =>
{
var counter = 5;
for (; counter > 0; counter--)
{
Console.WriteLine(counter);
Thread.Sleep(1000);
}
throw new InvalidCastException("I threw up!");
});
GC.Collect();
GC.WaitForPendingFinalizers();
Console.ReadLine();
}
private static void SetupUnobservedTaskExceptionHandling()
{
TaskScheduler.UnobservedTaskException += OnTaskException;
}
private static void OnTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
Console.WriteLine("Error!" + e.Exception);
e.SetObserved();
}
You are not waiting for the task to finish executing. That means that your app will end before the task throws an exception.
If you simply add a Thread.Sleep
and let the task throw the exception you will be notified:
private static void Main()
{
SetupUnobservedTaskExceptionHandling();
Task.Factory.StartNew(() =>
{
var counter = 5;
for (; counter > 0; counter--)
{
Console.WriteLine(counter);
Thread.Sleep(1000);
}
throw new InvalidCastException("I threw up!");
});
Thread.Sleep(10000);
GC.Collect();
GC.WaitForPendingFinalizers();
Console.ReadLine();
}