Dave New
Dave New

Reputation: 40092

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?

Upvotes: 12

Views: 11560

Answers (2)

Peter Ritchie
Peter Ritchie

Reputation: 35869

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;
            }
    );

Upvotes: 10

go..
go..

Reputation: 948

sample

Task.Factory.StartNew(testMethod).ContinueWith(p =>
            {
                if (p.Exception != null)
                    p.Exception.Handle(x =>
                        {
                            Console.WriteLine(x.Message);
                            return false;
                        });
            });

Upvotes: 2

Related Questions