The code

Ο κώδικας

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

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

public void TestWait()
{
    var t = Task.Factory.StartNew(async () =>
    {
        Console.WriteLine("Start");
        await Task.Delay(5000);
        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
[0.0s] All done
[5.0s] Done      // only if the process is still alive

Why

Γιατί

All done prints immediately and if the program or the test ends right after, Done never prints at all. The reason is the type of t:

Task<Task> t = Task.Factory.StartNew(async () => { ... });

An async lambda is a Func<Task>. StartNew has no special overload for it, so it uses StartNew<TResult>(Func<TResult>) with TResult being Task. Now there are two tasks:

  • The outer task (t) means "run the delegate until it returns". The delegate prints Start, hits await and returns an incomplete task right there. So the outer task completes after a few microseconds.
  • The inner task (t.Result) is the real work. It completes five seconds later.

t.Wait() waits only for the outer task. You can see it right after the wait:

Console.WriteLine(t.Status);        // RanToCompletion
Console.WriteLine(t.Result.Status); // WaitingForActivation

Why is StartNew like this? It arrived in .NET 4.0 in 2010, two years before async existed. To StartNew a returned Task is just a value like an int. Two more consequences: an exception thrown after the await goes into the inner task and t.Wait() never throws it. And writing Task t = ... instead of var compiles fine and hides the bug completely.

Το All done τυπώνεται αμέσως και αν το πρόγραμμα ή το test τελειώσει αμέσως μετά, το Done δεν τυπώνεται ποτέ. Ο λόγος είναι ο τύπος του t:

Task<Task> t = Task.Factory.StartNew(async () => { ... });

Ένα async lambda είναι Func<Task>. Το StartNew δεν έχει ειδικό overload γι' αυτό, οπότε χρησιμοποιεί το StartNew<TResult>(Func<TResult>) με TResult το Task. Τώρα υπάρχουν δύο tasks:

  • Το εξωτερικό task (t) σημαίνει "τρέξε το delegate μέχρι να επιστρέψει". Το delegate τυπώνει Start, φτάνει στο await και επιστρέφει εκεί ένα μη ολοκληρωμένο task. Άρα το εξωτερικό task ολοκληρώνεται μετά από λίγα microseconds.
  • Το εσωτερικό task (t.Result) είναι η πραγματική δουλειά. Ολοκληρώνεται πέντε δευτερόλεπτα αργότερα.

Το t.Wait() περιμένει μόνο το εξωτερικό task. Το βλέπεις αμέσως μετά το wait:

Console.WriteLine(t.Status);        // RanToCompletion
Console.WriteLine(t.Result.Status); // WaitingForActivation

Γιατί είναι έτσι το StartNew; Ήρθε στο .NET 4.0 το 2010, δύο χρόνια πριν υπάρξει το async. Για το StartNew ένα Task που επιστρέφεται είναι απλώς μια τιμή σαν ένα int. Δύο ακόμα συνέπειες: ένα exception μετά το await πηγαίνει στο εσωτερικό task και το t.Wait() δεν το πετάει ποτέ. Και αν γράψεις Task t = ... αντί για var, γίνεται compile κανονικά και το bug κρύβεται εντελώς.

Remember

Να θυμάσαι

StartNew with an async lambda returns Task<Task>. Waiting on it waits only until the first await.

Το StartNew με async lambda επιστρέφει Task<Task>. Αν το περιμένεις, περιμένεις μόνο μέχρι το πρώτο await.