Reputation: 40092
What is the best way to handle exceptions thrown somewhere in a task continuation?
For example, I have a simple task continuation below (updateMessages
-> updateInterface
) but in reality this could be a chain of more than 2 tasks. I want to have a generic exception "catch all" task which continues from any fault which could occur in the chain.
How I'm doing this is by defining an Action
(which observes and logs the exception) and continuing from each task with TaskContinuationOptions.OnlyOnFaulted
set. Is there perhaps a better way of doing this?
Task updateMessages = Task.Factory.StartNew(() =>
{
// Do stuff
});
Task updateInterface = updateMessages.ContinueWith(task =>
{
// UI updates
},
System.Threading.CancellationToken.None,
TaskContinuationOptions.NotOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
Action<Task> failureAction = new Action<Task>(failedTask =>
{
// Observe and log exceptions
});
updateMessages.ContinueWith(failureAction, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
updateInterface.ContinueWith(failureAction, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext());
Upvotes: 3
Views: 1432
Reputation: 17474
Your approach is the approach I use, and it works well.
A couple of asides that aren't about the question:
Upvotes: 3