I noticed that exceptions thrown from a thread other than my main application thread are not caught by the DispatcherUnhandledException event handler. So I have to manually throw them like this:
Task.Factory.StartNew(() =>
{
throw new Exception("oops! something went wrong...");
}).ContinueWith((task) =>
{
if (task.IsFaulted)
{
App.Current.Dispatcher.Invoke(new Action(() =>
{
throw task.Exception.InnerExceptions.First();
}));
}
});
However, I don’t want to add the above ContinueWith method to every single Task I create. I would rather have some way for this to be handled automatically.
The following class solves this problem:
Now I can simply use the following code (exactly the same as the Task class):
Unlike the Task class, however, any exception thrown from one of these threads will be AUTOMATICALLY caught by my DispatcherUnhandledException event handler.