Observing Task exceptions within a ContinueWith

Viewed 11312

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?

2 Answers
Related