什么是&QUOT的目的;返回计谋"在C#中? [英] What is the purpose of "return await" in C#?

查看:443
本文介绍了什么是&QUOT的目的;返回计谋"在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();
}

将使感?

为什么要用返回待机结构时,你可以直接返回任务&LT; T&GT; 从内 DoAnotherThingAsync()调用?

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

我看code与返回待机在很多地方,我想我应该已经错过了一些东西。但据我了解,没有使用异步/等待关键字在这种情况下,直接返回任务在功能上等同。为什么要添加额外的附加开销等待图层?

I see code with return await in so many places, I think I should 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?

推荐答案

有一个鬼鬼祟祟的情况下,当返回在正常的方法和返回计谋异步方法不同的表现:在使用(或者更一般地说,任何与 返回待机尝试块)。

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

第一种方法是将的Dispose()对象一旦 DoAnotherThingAsync ()方法的返回值,这很可能是长期实际完成之前。这意味着第一个版本可能是越野车(因为布置得太早),而第二个版本将正常工作。

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.

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

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