简体   繁体   中英

Why is only one from many exceptions from child tasks always propagated?

I am struggling to better grasp the rationale of exception and error handling in TPL (and with some more luck in .NET 4.5 async/await tasks)

The slightly modified from my earlier question "How to better understand the code/statements from "Async - Handling multiple Exceptions" article?" C# console app code running 2 detached inner nested attached (dependent) child (Update: sorry, started one question but ended by another!) tasks:

class Program
{  
   static void Main(string[] args)
   {  Tst();
      Console.ReadLine();
   }
   async static Task  Tst()
   {
       try
       {
           await Task.Factory.StartNew
             (() =>
                {
                   Task.Factory.StartNew
                       (   () => { 
                                    Console.WriteLine("From 1st child");
                                    throw new NullReferenceException(); 
                                  }
                            , TaskCreationOptions.AttachedToParent
                        );
               Task.Factory.StartNew
                       (  () =>
                               { 
                                   Console.WriteLine("From 2nd child");
                                   throw new ArgumentException(); 
                               }
      ,TaskCreationOptions.AttachedToParent
                       );
                }
             );
    }
    catch (AggregateException ex)
    {
        Console.WriteLine("** {0} **", ex.GetType().Name);
        foreach (var exc in ex.Flatten().InnerExceptions)
        {
             Console.WriteLine(exc.GetType().Name);
        }
    }
    catch (Exception ex)
    {
       Console.WriteLine("## {0} ##", ex.GetType().Name);
    }
 } 

produces output that alternates (non-deterministically) between:

From 1st child
From 2nd child
** AggregateException **
ArgumentException

and

From 1t child
From 2nd child
** AggregateException **
NullReferenceException

Seems like always one and only one exception from one of a child tasks always propagated/caught.

Why is only one exception propagated/caught?
I'd have better understood if none or rather all exceptions from child tasks are always caught

Is it possible, in this situation, that both or none exception will be caught?

You should not mix parent/child tasks with async . They were not designed to go together.

svick already answered this question as part of his (correct) answer to your other question . Here's how you can think of it:

  • Each inner StartNew gets one exception, which is wrapped into an AggregateException and placed on the returned Task .
  • The outer StartNew gets both AggregateException s from its child tasks, which it wraps into another AggregateException on its returned Task .
  • When you await a Task , the first inner exception is raised. Any others are ignored.

You can observe this behavior by saving the Task s and inspecting them after the exception is raised by await :

async static Task Test()
{
    Task containingTask, nullRefTask, argTask;
    try
    {
        containingTask = Task.Factory.StartNew(() =>
        {
            nullRefTask = Task.Factory.StartNew(() =>
            {
                throw new NullReferenceException();
            }, TaskCreationOptions.AttachedToParent);
            argTask = Task.Factory.StartNew(() =>
            {
                throw new ArgumentException();
            }, TaskCreationOptions.AttachedToParent);
        });
        await containingTask;
    }
    catch (AggregateException ex)
    {
        Console.WriteLine("** {0} **", ex.GetType().Name);
    }
}

If you put a breakpoint on WriteLine , you can see that the exceptions from both child tasks are being placed on the parent task. The await operator only propagates one of them, so that's why you only catch one.

From what I can deduce the reason this occurs is that the await signals that task to wait for the task to finish. When an exception is thrown, the task is finished (since an exception crashes it) and the exception propagates outwards to your async function where it will be caught. This means that you will always catch one exception with this setup.

To always catch both, remove await and instead use Task.Factory.StartNew(..).Wait(); The Wait function will keep a count of all child processes and will not return until all of them have finished. Since multiple exceptions are thrown (one from each child) they are bundled in a new AggregateException, which later is caught and its children are flattened and the inner exceptions are printed. This should give you the output:

From 1st child
From 2nd child
** AggregateException **
ArgumentException
NullReferenceException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM