简体   繁体   English

异步/等待的呼叫链...等待等待或返回等待?

[英]Call chain for async/await … await the awaitable or return the awaitable?

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 ? 并通过中间方法调用它,中间方法是等待异步方法IntermediateA还是只返回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. 我可以告诉调试器,两者看起来完全相同,但在我看来,IntermediateB应该通过避免在状态机中等待一个等待条目来更好地执行。

Is that right? 是对的吗?

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. 如果您await失败的任务,则会在该方法中抛出异常,但如果您将该方法传递给该方法然后await它,那么将在consumer方法中抛出异常。 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. 另一个区别是更罕见的,在消费者等待任务的情况下,如果它发生延迟,则任务可以在等待点完成并绕过状态机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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