The code

Ο κώδικας

What does this print and in which order? Decide before you scroll down.

Τι τυπώνει και με ποια σειρά; Αποφάσισε πριν προχωρήσεις παρακάτω.

var t = Task.Run(() => int.Parse("abc"));

try { t.Wait(); }
catch (Exception ex) { Console.WriteLine(ex.GetType().Name); }

try { await t; }
catch (Exception ex) { Console.WriteLine(ex.GetType().Name); }

Run it yourself:

Τρέξ' το μόνος σου:

Live example, editable, runs on .NET Fiddle
Ζωντανό παράδειγμα, επεξεργάσιμο, τρέχει στο .NET Fiddle

The answer

Η απάντηση

AggregateException
FormatException

Why

Γιατί

  1. int.Parse("abc") throws FormatException on a pool thread. The process does not crash: the task stores the exception and becomes Faulted.
  2. t.Wait() throws an AggregateException with the FormatException inside it.
  3. await t unwraps and throws the original FormatException with its stack trace.
  4. A faulted task stays faulted, so every Wait, Result or await on it throws again.

Wait() and Result come from .NET 4.0, where one task could hold several errors, so they always wrap. await was designed to feel like synchronous code, so it throws the real type. The classic bug:

try { t.Wait(); }
catch (FormatException) { } // never runs: Wait throws AggregateException

t.Result also throws AggregateException. t.GetAwaiter().GetResult() throws FormatException like await but still blocks the thread.

  1. Το int.Parse("abc") πετάει FormatException σε ένα thread του pool. Το process δεν πέφτει: το task αποθηκεύει το exception και γίνεται Faulted.
  2. Το t.Wait() πετάει ένα AggregateException με το FormatException μέσα του.
  3. Το await t ξετυλίγει και πετάει το αρχικό FormatException με το stack trace του.
  4. Ένα faulted task μένει faulted, οπότε κάθε Wait, Result ή await πάνω του πετάει ξανά.

Τα Wait() και Result προέρχονται από το .NET 4.0, όπου ένα task μπορούσε να κρατά πολλά σφάλματα, οπότε τυλίγουν πάντα. Το await σχεδιάστηκε να μοιάζει με synchronous κώδικα, οπότε πετάει τον πραγματικό τύπο. Το κλασικό bug:

try { t.Wait(); }
catch (FormatException) { } // never runs: Wait throws AggregateException

Το t.Result πετάει επίσης AggregateException. Το t.GetAwaiter().GetResult() πετάει FormatException όπως το await αλλά κάνει ακόμα block το thread.

Remember

Να θυμάσαι

Wait() and Result throw AggregateException. await throws the original exception.

Τα Wait() και Result πετούν AggregateException. Το await πετάει το αρχικό exception.