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:
Τρέξ' το μόνος σου:
The answer
Η απάντηση
AggregateException
FormatException
Why
Γιατί
int.Parse("abc")throwsFormatExceptionon a pool thread. The process does not crash: the task stores the exception and becomesFaulted.t.Wait()throws anAggregateExceptionwith theFormatExceptioninside it.await tunwraps and throws the originalFormatExceptionwith its stack trace.- A faulted task stays faulted, so every
Wait,Resultorawaiton 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.
- Το
int.Parse("abc")πετάειFormatExceptionσε ένα thread του pool. Το process δεν πέφτει: το task αποθηκεύει το exception και γίνεταιFaulted. - Το
t.Wait()πετάει έναAggregateExceptionμε τοFormatExceptionμέσα του. - Το
await tξετυλίγει και πετάει το αρχικόFormatExceptionμε το stack trace του. - Ένα 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.