简体   繁体   中英

Difference between await function call and await Task

In the following example there are two ways of calling code enter link description here

        Task<Egg> taskEggs = FryEggsAsync(2);
        Egg eggs = await taskEggs;

Such code runs parallel, but

Egg eggs = await FryEggsAsync(2);

Runs asynchronously, but sequentially. I was always using WaitAll , but was surprised, that following example also runs parallel:

        var taskEggs = FryEggsAsync(2);
        var taskBacon = FryBaconAsync(3);
        var taskToast = ToastBreadAsync(2);

        Toast toast = await taskToast;
        //Toast toast = await ToastBreadAsync(2); 
        ApplyButter(toast);
        ApplyJam(toast);
        Console.WriteLine("toast is ready");

        Egg eggs = await taskEggs;
        //Egg eggs = await FryEggsAsync(2);
        Console.WriteLine("eggs are ready");

        Bacon bacon = await taskBacon;
        //Bacon bacon = await FryBaconAsync(3);
        Console.WriteLine("bacon is ready");

        Juice oj = PourOJ();
        Console.WriteLine("oj is ready");
        Console.WriteLine("Breakfast is ready!\n");

How such difference can be explained?

Suppose you have the following code:

public class Person{
  public static string GetName(){
    return "John";
  }
}

What do you suppose the different is between the following codes:

Console.WriteLine(Person.GetName());

And

string x = Person.GetName();
Console.WriteLine(x);

Hopefully you can see that it's essentially no difference; you'll see "John" in the console either way...

... and that's all your codes are doing; the method returns a Task, and whether you store that Task in a variable and then await the variable, or whether you await the returned Task, you're still awaiting a Task returned by the call

The only significant different in storing the Task allows you to do some other stuff and then start awaiting the Task. If you're starting 10 tasks and stashing them in a list then Task.WhenAll'ing them that counts as "doing other stuff before you start awaiting"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM