The code

Ο κώδικας

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

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

public void TestWait()
{
    var t = Task.Factory.StartNew(() =>
    {
        Console.WriteLine("Start");
        Task.Delay(5000).Wait();
        Console.WriteLine("Done");
    });
    t.Wait();
    Console.WriteLine("All done");
}

Run it yourself:

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

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

The answer

Η απάντηση

[0.0s] Start
[5.0s] Done
[5.0s] All done

Why

Γιατί

The lambda has no async and returns nothing, so the compiler treats it as an Action and StartNew returns a plain Task.

  1. A ThreadPool thread runs the lambda and prints Start.
  2. Task.Delay(5000).Wait() blocks that pool thread for five seconds. It does nothing but nobody else can use it.
  3. Meanwhile the calling thread reaches t.Wait() and blocks too.
  4. After five seconds the lambda prints Done and returns. Only now is t complete.
  5. t.Wait() returns and All done prints.

The order is correct but two threads sit blocked for five seconds just to wait for a timer. In a console app nobody notices. In a web server under load this is the pattern that leads to ThreadPool starvation.

Το lambda δεν έχει async και δεν επιστρέφει τίποτα, οπότε ο compiler το βλέπει ως Action και το StartNew επιστρέφει ένα απλό Task.

  1. Ένα thread του ThreadPool τρέχει το lambda και τυπώνει Start.
  2. Το Task.Delay(5000).Wait() κάνει block εκείνο το thread για πέντε δευτερόλεπτα. Δεν κάνει τίποτα αλλά κανείς άλλος δεν μπορεί να το χρησιμοποιήσει.
  3. Στο μεταξύ το thread που καλεί φτάνει στο t.Wait() και κάνει κι αυτό block.
  4. Μετά από πέντε δευτερόλεπτα το lambda τυπώνει Done και επιστρέφει. Μόνο τώρα ολοκληρώνεται το t.
  5. Το t.Wait() επιστρέφει και τυπώνεται το All done.

Η σειρά είναι σωστή αλλά δύο threads κάθονται blocked για πέντε δευτερόλεπτα μόνο και μόνο για να περιμένουν έναν timer. Σε μια console εφαρμογή δεν το προσέχει κανείς. Σε έναν web server με φορτίο αυτό είναι το pattern που οδηγεί σε ThreadPool starvation.

Remember

Να θυμάσαι

Correct order, but every .Wait() holds a whole thread that does nothing.

Σωστή σειρά, αλλά κάθε .Wait() κρατά ένα ολόκληρο thread που δεν κάνει τίποτα.