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.
One way to solve this, is by rethrowing the Exception in a Lambda expression contained within the statement. Something like:
I don’t recommend that though as it is a bit foul, but it does answer the question!
You could alternatively do something similarly as nasty with SynchronizationContext.Post.