Does compiler perform “return value optimization” on chains of async methods

前端 未结 2 753
陌清茗
陌清茗 2021-01-12 07:16

Not return value optimization in the traditional sense, but I was wondering when you have a situation like this:

private async Task Method1()
{
    await Met         


        
2条回答
  •  北海茫月
    2021-01-12 07:57

    Why do you ask a question you can answer in a minute by simply testing it?

    class Program
    {
        static void Main(string[] args)
        {
            MainAsync().Wait();
            Console.ReadLine();
        }
    
        static async Task MainAsync()
        {
            await Method1();
        }
    
        static async Task Method1()
        {
            await Method2();
        }
    
        static async Task Method2()
        {
            await Method3();
        }
    
        static async Task Method3()
        {
            Console.Write("Start");
            await Task.Delay(1000);
            Console.Write("End");
        }
    }
    

    This creates four different state machines in IL.

    The IL code has to be this way, since you can call the methods from anywhere and they have to behave consistently, so any optimization would have to be done on the JIT level, not the C# compiler. If you don't need await, don't use it - that's your responsibility.

    A great example would be method overloads:

    static Task Method()
    {
      return Method("Default");
    }
    
    static async Task Method(string someString)
    {
      await SomeThingAsync(someString);
    }
    

    It's still just as asynchronous as if you did another await in the parameter-less method - but it avoids a useless state machine.

    The only purpose of the async keyword is to allow you to use the await keyword inside a given method. You can still await a method that isn't async - the requirement is returning Task, not having the async keyword.

    Using the same example as before, the awaits are superfluous. A simpler way would be this:

    class Program
    {
        static void Main(string[] args)
        {
            MainAsync().Wait();
            Console.ReadLine();
        }
    
        static async Task MainAsync()
        {
            await Method1();
            await Method2();
        }
    
        static Task Method1()
        {
            return Method2();
        }
    
        static Task Method2()
        {
            return Method3();
        }
    
        static async Task Method3()
        {
            Console.Write("Start");
            await Task.Delay(1000);
            Console.Write("End");
        }
    }
    

提交回复
热议问题