什么是&QUOT的目的;返回计谋"在C#中?目的、计谋、QUOT

由网友(ヤ未央мo寒メ)分享简介:时有任何场景,这样的写作方式:Is there any scenario where writing method like this:public async Task DoSomethingAsync(){// Some synchronous code might or might...

时有任何场景,这样的写作方式:

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.

阅读全文

相关推荐

最新文章