The code
Ο κώδικας
What does this print and in which order? Decide before you scroll down.
Τι τυπώνει και με ποια σειρά; Αποφάσισε πριν προχωρήσεις παρακάτω.
async Task<int> GetAsync(int x)
{
Thread.Sleep(1000);
return x;
}
var sw = Stopwatch.StartNew();
var t1 = GetAsync(1);
var t2 = GetAsync(2);
var c = await t1;
var d = await t2;
Console.WriteLine($"Β: {sw.ElapsedMilliseconds}");
Run it yourself:
Τρέξ' το μόνος σου:
The answer
Η απάντηση
Β: 2015
Why
Γιατί
Two seconds again, even though the tasks are started before they are awaited. An async method runs synchronously on the calling thread until it reaches an await on something that is not finished yet. This method never does. So GetAsync(1) sleeps for a full second before it even returns its task and only then does GetAsync(2) start.
The compiler warns you with CS1998: "This async method lacks 'await' operators and will run synchronously".
Πάλι δύο δευτερόλεπτα, παρόλο που τα tasks ξεκινούν πριν γίνει await. Μια async μέθοδος τρέχει synchronous στο thread αυτού που την καλεί μέχρι να φτάσει σε ένα await πάνω σε κάτι που δεν έχει τελειώσει ακόμα. Αυτή η μέθοδος δεν φτάνει ποτέ. Άρα το GetAsync(1) κοιμάται ένα ολόκληρο δευτερόλεπτο πριν καν επιστρέψει το task του και μόνο τότε ξεκινά το GetAsync(2).
Ο compiler σε προειδοποιεί με το CS1998: "This async method lacks 'await' operators and will run synchronously".
Remember
Να θυμάσαι
Writing async does not make a method run in the background. Only a real asynchronous operation inside it does.
Το async δεν κάνει μια μέθοδο να τρέχει στο παρασκήνιο. Μόνο μια πραγματική ασύγχρονη λειτουργία μέσα της το κάνει.