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

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

Is there any scenario where writing method like this:

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


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 07:43

    This also confuses me and I feel that the previous answers overlooked your actual question:

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

    Well sometimes you actually want a Task, but most time you actually want an instance of SomeType, that is, the result from the task.

    From your code:

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

    A person unfamiliar with the syntax (me, for example) might think that this method should return a Task, but since it is marked with async, it means that its actual return type is SomeResult. If you just use return foo.DoAnotherThingAsync(), you'd be returning a Task, which wouldn't compile. The correct way is to return the result of the task, so the return await.

提交回复
热议问题