The code
Ο κώδικας
What does this print and in which order? Decide before you scroll down.
Τι τυπώνει και με ποια σειρά; Αποφάσισε πριν προχωρήσεις παρακάτω.
var x = Task.Run(() => throw new InvalidOperationException("one"));
var y = Task.Run(() => throw new ArgumentException("two"));
var all = Task.WhenAll(x, y);
try
{
await all;
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name);
Console.WriteLine(all.Exception!.InnerExceptions.Count);
}
The answer
Η απάντηση
ArgumentException
2
Why
Γιατί
await throws only one exception: the first one stored in the task. In this run it was the ArgumentException, but which one comes first is not something to rely on.
The other exception is not lost. Task.WhenAll waits for every task to finish and keeps all their exceptions on the returned task. You read them from all.Exception.InnerExceptions inside the catch:
foreach (var inner in all.Exception!.InnerExceptions)
Console.WriteLine($"{inner.GetType().Name}: {inner.Message}");
all.Wait() would instead throw one AggregateException with both inside.
Το await πετάει μόνο ένα exception: το πρώτο που είναι αποθηκευμένο στο task. Σε αυτή την εκτέλεση ήταν το ArgumentException, αλλά ποιο έρχεται πρώτο δεν είναι κάτι στο οποίο να βασίζεσαι.
Το άλλο exception δεν χάνεται. Το Task.WhenAll περιμένει να τελειώσουν όλα τα tasks και κρατά όλα τα exceptions τους στο task που επιστρέφει. Τα διαβάζεις από το all.Exception.InnerExceptions μέσα στο catch:
foreach (var inner in all.Exception!.InnerExceptions)
Console.WriteLine($"{inner.GetType().Name}: {inner.Message}");
Το all.Wait() αντίθετα θα πετούσε ένα AggregateException με τα δύο μέσα.
Remember
Να θυμάσαι
await Task.WhenAll throws one exception. All of them are in task.Exception.InnerExceptions.
Το await Task.WhenAll πετάει ένα exception. Όλα βρίσκονται στο task.Exception.InnerExceptions.