.NET 4.0 Tasks: Rethrow Exception to UI Thread in Task.ContinueWith

Viewed 2716

I have a WPF application, where I make a long-running WCF call using the System.Threading.Tasks. I catch unhandled exceptions by adding a handler to Application.Current.DispatcherUnhandledException.

I create a task, where the ContinueWith function runs on the UI thread using the following code:

var task = new Task<T>(func).ContinueWith(t =>
{
    if (t.IsFaulted)
    {
        throw t.Exception.GetBaseException();
    }
    else
    {
        // Show t.Result on UI
    }
}, TaskScheduler.FromCurrentSynchronizationContext());

When an exception occurs in the task, I would like to rethrow the exception so that the DispatcherUnhandledException handler can handle it. But when I rethrow the exception, as shown above, it crashes my app and the DispatcherUnhandledException is not invoked.

How do I rethrow the exception on the UI thread so that the DispatcherUnhandledException handler is invoked?

When I was using the BackgroundWorker, rethrowing the exception did exactly this. Basically, I am looking to replace BackgroundWorker with Task, since Task has some really nice features I would like to take advantage of.

2 Answers
Related