Dave New
Dave New

Reputation: 40092

Handle exception thrown somewhere in a task continuation

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

Answers (1)

Matt Smith
Matt Smith

Reputation: 17474

Your approach is the approach I use, and it works well.

A couple of asides that aren't about the question:

  • Does your failureAction really need to run on the main UI thread?
  • I'd write a helper method to attach the failure continuation since you're going to be doing this with every task.

Upvotes: 3

Related Questions