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

Γιατί

  1. DoWorkAsync() runs synchronously on the calling thread and prints 1.
  2. At await Task.Delay(1000) it returns an incomplete task. The caller ignores it and prints A.
  3. The caller awaits two seconds. After one second the timer of DoWorkAsync fires and 2 prints on a pool thread.
  4. After two seconds B prints.

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".

  1. Το DoWorkAsync() τρέχει synchronous στο thread αυτού που το καλεί και τυπώνει 1.
  2. Στο await Task.Delay(1000) επιστρέφει ένα μη ολοκληρωμένο task. Αυτός που το κάλεσε το αγνοεί και τυπώνει A.
  3. Αυτός που το κάλεσε κάνει await δύο δευτερόλεπτα. Μετά από ένα δευτερόλεπτο χτυπά ο timer του DoWorkAsync και το 2 τυπώνεται σε thread του pool.
  4. Μετά από δύο δευτερόλεπτα τυπώνεται το 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.