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

前端 未结 2 756
陌清茗
陌清茗 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 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.

提交回复
热议问题