Call chain for async/await … await the awaitable o

2019-05-02 20:37发布

Given an async method:

public async Task<int> InnerAsync()
{
    await Task.Delay(1000);
    return 123;
}

And calling it through an intermediate method, should the intermediate method await the async method IntermediateA or merely return the Task IntermediateB?

public async Task<int> IntermediateA()
{
    return await InnerAsync();
}

private Task<int> IntermediateB()
{
    return InnerAsync();
}

As best I can tell with the debugger, both appear to work exactly the same, but it seems to me that IntermediateB should perform better by avoiding one more await entry in the state machine.

Is that right?

1条回答
虎瘦雄心在
2楼-- · 2019-05-02 21:16

There is subtle differences in this two approaches. If you await failed task the exception will thrown in that method, but if you pass the task thought that method and then await it, the exception will be thrown in the consumer method. Another difference is more rare, in case of consumer awaiting the task and if it occurred with delay, the task can be finished at the await point and bypass the state machine.

查看更多
登录 后发表回答