“返回等待"的目的是什么?在 C# 中? [英] What is the purpose of "return await" in C#?

查看:37
本文介绍了“返回等待"的目的是什么?在 C# 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何场景可以编写这样的方法:

Is there any scenario where writing method like this:

public async Task<SomeResult> DoSomethingAsync()
{
    // Some synchronous code might or might not be here... //
    return await DoAnotherThingAsync();
}

而不是这个:

public Task<SomeResult> DoSomethingAsync()
{
    // Some synchronous code might or might not be here... //
    return DoAnotherThingAsync();
}

有意义吗?

当您可以从内部 DoAnotherThingAsync() 调用直接返回 Task 时,为什么要使用 return await 构造?

Why use return await construct when you can directly return Task<T> from the inner DoAnotherThingAsync() invocation?

我在很多地方看到带有 return await 的代码,我想我可能错过了一些东西.但据我所知,在这种情况下不使用 async/await 关键字并直接返回 Task 在功能上是等效的.为什么要增加额外的 await 层的额外开销?

I see code with return await in so many places, I think I might have missed something. But as far as I understand, not using async/await keywords in this case and directly returning the Task would be functionally equivalent. Why add additional overhead of additional await layer?

推荐答案

在普通方法returnasync<return await时,有一种偷偷摸摸的情况/code> 方法的行为有所不同:当与 using 结合使用时(或者,更一般地说,任何 return awaittry 块中).

There is one sneaky case when return in normal method and return await in async method behave differently: when combined with using (or, more generally, any return await in a try block).

考虑一个方法的这两个版本:

Consider these two versions of a method:

Task<SomeResult> DoSomethingAsync()
{
    using (var foo = new Foo())
    {
        return foo.DoAnotherThingAsync();
    }
}

async Task<SomeResult> DoSomethingAsync()
{
    using (var foo = new Foo())
    {
        return await foo.DoAnotherThingAsync();
    }
}

第一个方法将在 DoAnotherThingAsync() 方法返回后立即 Dispose() Foo 对象,这可能早在它之前实际上完成.这意味着第一个版本可能有问题(因为 Foo 被处理得太早),而第二个版本可以正常工作.

The first method will Dispose() the Foo object as soon as the DoAnotherThingAsync() method returns, which is likely long before it actually completes. This means the first version is probably buggy (because Foo is disposed too soon), while the second version will work fine.

这篇关于“返回等待"的目的是什么?在 C# 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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