A common problem I've seen has been managing unhandled exceptions inside of tasks. They don't cause a crash, they happen silently, and I can't even get an event to trigger when the task fails! I've seen users prescribe custom classes and stuff to handle this, my question is, is there a "standard" microsoft way to handle this?
For the sake of example, I made this simple console application (.NET 4.5.1) to demonstrate the problem. Can this be modified so that these tasks can be executed asynchronousyly, but call "handler" when it encounters an unhandled exception? Or at least crash? I thought this was what UnobservedTaskException is exactly supposed to do.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += Handler;
AppDomain.CurrentDomain.UnhandledException += Handler;
Task.Run(() => { throw new ApplicationException("I'll throw an unhandled exception"); });
Task.Factory.StartNew(() => { throw new ApplicationException("I'll throw an unhandled exception too"); });
System.Threading.Thread.Sleep(2000);
Console.WriteLine("I think everything is just peachy!");
System.Threading.Thread.Sleep(10000);
}
private static void Handler(Object sender, EventArgs e)
{
Console.WriteLine("I'm so lonely, won't anyone call me?");
}
}
}
Output:
I think everything is just peachy!
Desired output:
I'm so lonely, won't anyone call me?
I'm so lonely, won't anyone call me?
I think everything is just peachy!
And/or simply crashing, even that would be a tremendous improvement over the asynchronous task failing silently!
EDIT: added this to app.config per this MSDN article http://msdn.microsoft.com/en-us/library/jj160346%28v=vs.110%29.aspx, but no change:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime>
</configuration>