The code
Ο κώδικας
What does this print and in which order? Decide before you scroll down.
Τι τυπώνει και με ποια σειρά; Αποφάσισε πριν προχωρήσεις παρακάτω.
async Task DoWorkAsync()
{
Console.WriteLine("1");
await Task.Delay(1000);
Console.WriteLine("2");
}
DoWorkAsync(); // χωρίς await!
Console.WriteLine("A");
await Task.Delay(2000);
Console.WriteLine("B");
The answer
Η απάντηση
[ 0ms] 1
[ 5ms] A
[1021ms] 2
[2013ms] B
Why
Γιατί
DoWorkAsync()runs synchronously on the calling thread and prints1.- At
await Task.Delay(1000)it returns an incomplete task. The caller ignores it and printsA. - The caller awaits two seconds. After one second the timer of
DoWorkAsyncfires and2prints on a pool thread. - After two seconds
Bprints.
2 comes before B only because one second is shorter than two. Nothing waits for DoWorkAsync. Change Task.Delay(2000) to Task.Delay(500) and the output is 1, A, B: the program ends and 2 never prints. The compiler warns with CS4014: "Because this call is not awaited, execution of the current method continues before the call is completed".
- Το
DoWorkAsync()τρέχει synchronous στο thread αυτού που το καλεί και τυπώνει1. - Στο
await Task.Delay(1000)επιστρέφει ένα μη ολοκληρωμένο task. Αυτός που το κάλεσε το αγνοεί και τυπώνειA. - Αυτός που το κάλεσε κάνει await δύο δευτερόλεπτα. Μετά από ένα δευτερόλεπτο χτυπά ο timer του
DoWorkAsyncκαι το2τυπώνεται σε thread του pool. - Μετά από δύο δευτερόλεπτα τυπώνεται το
B.
Το 2 βγαίνει πριν από το B μόνο επειδή το ένα δευτερόλεπτο είναι λιγότερο από τα δύο. Τίποτα δεν περιμένει το DoWorkAsync. Άλλαξε το Task.Delay(2000) σε Task.Delay(500) και το output γίνεται 1, A, B: το πρόγραμμα τελειώνει και το 2 δεν τυπώνεται ποτέ. Ο compiler προειδοποιεί με το CS4014: "Because this call is not awaited, execution of the current method continues before the call is completed".
Remember
Να θυμάσαι
Without await nobody waits for the work. await DoWorkAsync() gives 1, 2, A, B.
Χωρίς await κανείς δεν περιμένει τη δουλειά. Το await DoWorkAsync() δίνει 1, 2, A, B.