The code

Ο κώδικας

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

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

public async Task TestWaitAsync()
{
    Console.WriteLine("Start");
    await Task.Delay(5000);
    Console.WriteLine("Done");
    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

Γιατί

Same output as exercises 1 and 4, but now zero threads are blocked during the five seconds. The method gives its thread back at the await and continues when the timer fires.

There is no Task.Run at all because a delay is not CPU work. There is nothing to move to another thread, only something to wait for. await waits without holding a thread. Every modern test framework (xUnit, NUnit and MSTest) supports async Task test methods, so a test never needs .Wait().

When you do have real CPU work to move off a UI thread, keep Task.Run but await it:

var report = await Task.Run(() => BuildReport(data));

Ίδιο output με τις ασκήσεις 1 και 4, αλλά τώρα κανένα thread δεν είναι blocked στα πέντε δευτερόλεπτα. Η μέθοδος επιστρέφει το thread της στο await και συνεχίζει όταν χτυπήσει ο timer.

Δεν υπάρχει καθόλου Task.Run γιατί ένα delay δεν είναι δουλειά CPU. Δεν υπάρχει τίποτα να μεταφερθεί σε άλλο thread, μόνο κάτι να περιμένεις. Το await περιμένει χωρίς να κρατά thread. Κάθε σύγχρονο test framework (xUnit, NUnit και MSTest) υποστηρίζει test μεθόδους async Task, οπότε ένα test δεν χρειάζεται ποτέ .Wait().

Όταν έχεις πραγματική δουλειά CPU να βγάλεις από ένα UI thread, κράτα το Task.Run αλλά κάνε του await:

var report = await Task.Run(() => BuildReport(data));

Remember

Να θυμάσαι

The best version has no Task.Run and no .Wait(): an async Task method that awaits.

Η καλύτερη εκδοχή δεν έχει ούτε Task.Run ούτε .Wait(): μια μέθοδος async Task που κάνει await.