Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observing Task exceptions within a ContinueWith

There are various ways in which to observe exceptions thrown within tasks. One of them is in a ContinueWith with OnlyOnFaulted:

var task = Task.Factory.StartNew(() =>
{
    // Throws an exception 
    // (possibly from within another task spawned from within this task)
});

var failureTask = task.ContinueWith((t) =>
{
    // Flatten and loop (since there could have been multiple tasks)
    foreach (var ex in t.Exception.Flatten().InnerExceptions)
        Console.WriteLine(ex.Message);
}, TaskContinuationOptions.OnlyOnFaulted);

My question: Do the exceptions become automatically observed once failureTask begins or do they only become observed once I 'touch' ex.Message?

like image 228
Dave New Avatar asked Jul 31 '12 15:07

Dave New


People also ask

How to handle exceptions in Task?

Exceptions are propagated when you use one of the static or instance Task. Wait methods, and you handle them by enclosing the call in a try / catch statement. If a task is the parent of attached child tasks, or if you are waiting on multiple tasks, multiple exceptions could be thrown.

What happens when a Task throws an exception?

When exceptions happen, all the exceptions are re-thrown by the calling thread. To do that they're wrapped inside AggregateException and returned to the caller. So when we await a task, we only get the first exception from a collection of exceptions that might exist on a task.

What does calling Task ContinueWith () do?

ContinueWith(Action<Task,Object>, Object, TaskScheduler)Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes.

What is ContinueWith C#?

The ContinueWith function is a method available on the task that allows executing code after the task has finished execution. In simple words it allows continuation. Things to note here is that ContinueWith also returns one Task. That means you can attach ContinueWith one task returned by this method.


1 Answers

They are viewed as observed once you access the Exception property.

See also AggregateException.Handle. You can use t.Exception.Handle instead:

t.Exception.Handle(exception =>
            {
            Console.WriteLine(exception);
            return true;
            }
    );
like image 168
Peter Ritchie Avatar answered Sep 22 '22 08:09

Peter Ritchie