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

前端 未结 2 754
陌清茗
陌清茗 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");
        }
    }
    
    0 讨论(0)
  • 2021-01-12 08:00

    No, the C# compiler doesn't optimize it and it should not. These are conceptually two different things, here is a similar question.

    IMO, the major difference is in how exceptions are getting propogated into the caller of Method1 and Method2. I demo'ed this behavoir here.

    In the first case (without the state machine), an exception will be immediately thrown on the caller's stack frame. If it is unhanded, the app may crash right away (unless there is another async method in the chain of calls on the same stack frame).

    In the second case (with the state machine), an exception will remain dormant in the Task object returned to the caller, until it is observed via await task or task.Wait(), some time later. It may get observed on a completely different stack frame, or may not get observed at all. I posted some more details about this here.

    0 讨论(0)
提交回复
热议问题