Gendolph
Gendolph

Reputation: 473

How to handle different Task exceptions with Wait() of parent and child.ContinueWith?

I have some hierarchy of parent/child tasks:

var t1 = Task.Factory.StartNew(() =>
    {
        var t21 = Task.Factory.StartNew(() =>
            {
                throw new Exception("Inner fault");
            }, TaskCreationOptions.AttachedToParent);

        var t22 = t21.ContinueWith(ant =>
            {
                Console.WriteLine("Inner handler: " + ant.Exception.InnerException.Message);
            }, TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.OnlyOnFaulted);

        throw new Exception("Outer fault");
    });

try
{
    t1.Wait();
}
catch (AggregateException ae)
{
    foreach (var e in ae.Flatten().InnerExceptions)
        Console.WriteLine("Outer handler: " + e.Message);
}

As result, "Outer handler" handles exception that had been already handled by "Inner handler":

Inner handler: Inner fault
Outer handler: Outer fault
Outer handler: Inner fault

Is it possible to prevent handling of already handled exceptions in "Outer handle" ("Inner handler" in my example)?

Upvotes: 1

Views: 204

Answers (1)

Benoit Blanchon
Benoit Blanchon

Reputation: 14571

It works if you remove TaskCreationOptions.AttachedToParent on t21.

In that case you may want to add t22.Wait() in t1 to reproduce the behavior of the attached child task.

Upvotes: 1

Related Questions