异步/等待的调用链...等待等待还是返回等待? [英] Call chain for async/await ... await the awaitable or return the awaitable?

查看:104
本文介绍了异步/等待的调用链...等待等待还是返回等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个异步方法:

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

并通过中间方法调用它,中间方法应该等待异步方法IntermediateA还是只返回Task IntermediateB?

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();
}

尽我所能告诉调试器,两者看上去工作完全相同,但在我看来,IntermediateB应该通过避免在状态机中再进入一个等待项来实现更好的性能.

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.

对吗?

推荐答案

这两种方法之间存在细微的差异.如果await任务失败,则将在该方法中引发异常,但是如果让任务传递该方法然后又await认为该异常,则将在使用者方法中引发该异常.如果消费者等待任务,并且延迟发生,则可以在等待点完成任务并绕过状态机,这是另一种差异更为罕见.

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.

这篇关于异步/等待的调用链...等待等待还是返回等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆