I’m reading through a book about the C# Task Parallel Library and have the following example but the TaskScheduler.UnobservedTaskException handler is never being triggered. Can anyone give me any clues as to why?
TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) =>
{
eventArgs.SetObserved();
((AggregateException)eventArgs.Exception).Handle(ex =>
{
Console.WriteLine("Exception type: {0}", ex.GetType());
return true;
});
};
Task task1 = new Task(() =>
{
throw new ArgumentNullException();
});
Task task2 = new Task(() => {
throw new ArgumentOutOfRangeException();
});
task1.Start();
task2.Start();
while (!task1.IsCompleted || !task2.IsCompleted)
{
Thread.Sleep( 5000 );
}
Console.WriteLine("done");
Console.ReadLine();
Unfortunately, that example will never show you your code. The
UnobservedTaskExceptionwill only happen if a Task gets collected by the GC with an exception unobserved – as long as you hold a reference totask1andtask2, the GC will never collect, and you’ll never see your exception handler.In order to see the behavior of the
UnobservedTaskExceptionin action, I’d try the following (contrived example):This will show you your messages. The first
Thread.Sleep(100)call provides enough time for the tasks to throw. The collect and wait forces a GC collection, which will fire your event handler 2x.