What is the purpose of “return await” in C#?

前端 未结 7 2240
半阙折子戏
半阙折子戏 2020-11-21 07:18

Is there any scenario where writing method like this:

public async Task DoSomethingAsync()
{
    // Some synchronous code          


        
7条回答
  •  难免孤独
    2020-11-21 07:34

    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 DoSomethingAsync()
    {
        using (var foo = new Foo())
        {
            return foo.DoAnotherThingAsync();
        }
    }
    
    async Task DoSomethingAsync()
    {
        using (var foo = new Foo())
        {
            return await foo.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.

提交回复
热议问题