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:
Τρέξ' το μόνος σου:
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.
- A ThreadPool thread runs the lambda and prints
Start. Task.Delay(5000).Wait()blocks that pool thread for five seconds. It does nothing but nobody else can use it.- Meanwhile the calling thread reaches
t.Wait()and blocks too. - After five seconds the lambda prints
Doneand returns. Only now istcomplete. t.Wait()returns andAll doneprints.
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.
- Ένα thread του ThreadPool τρέχει το lambda και τυπώνει
Start. - Το
Task.Delay(5000).Wait()κάνει block εκείνο το thread για πέντε δευτερόλεπτα. Δεν κάνει τίποτα αλλά κανείς άλλος δεν μπορεί να το χρησιμοποιήσει. - Στο μεταξύ το thread που καλεί φτάνει στο
t.Wait()και κάνει κι αυτό block. - Μετά από πέντε δευτερόλεπτα το lambda τυπώνει
Doneκαι επιστρέφει. Μόνο τώρα ολοκληρώνεται τοt. - Το
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 που δεν κάνει τίποτα.