The code

Ο κώδικας

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

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

public void TestWait()
{
    Task t = Task.Factory.StartNew(async () =>
    {
        Console.WriteLine("Start");
        await Task.Delay(5000);
        Console.WriteLine("Done");
    }).Unwrap();
    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

Γιατί

StartNew still returns Task<Task> as in the previous exercise. Unwrap() turns it into a single Task that completes only when the inner task completes. It also carries the inner task's exceptions, so an error after the await now reaches t.Wait().

The order is correct again. But look at what you wrote: "queue this async lambda to the ThreadPool and give me a task for the whole async operation". That is exactly what Task.Run does on its own, which is the next exercise.

Το StartNew επιστρέφει πάλι Task<Task> όπως στην προηγούμενη άσκηση. Το Unwrap() το μετατρέπει σε ένα μόνο Task που ολοκληρώνεται μόνο όταν ολοκληρωθεί το εσωτερικό task. Κουβαλά επίσης τα exceptions του εσωτερικού task, οπότε ένα σφάλμα μετά το await φτάνει πλέον στο t.Wait().

Η σειρά είναι πάλι σωστή. Αλλά δες τι έγραψες: "βάλε αυτό το async lambda στο ThreadPool και δώσε μου ένα task για όλη την async λειτουργία". Αυτό ακριβώς κάνει μόνο του το Task.Run, που είναι η επόμενη άσκηση.

Remember

Να θυμάσαι

Unwrap() fixes Task<Task>, but it is a handwritten Task.Run.

Το Unwrap() διορθώνει το Task<Task>, αλλά είναι ένα χειροποίητο Task.Run.