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

前端 未结 7 2231
半阙折子戏
半阙折子戏 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:47

    If you don't need async (i.e., you can return the Task directly), then don't use async.

    There are some situations where return await is useful, like if you have two asynchronous operations to do:

    var intermediate = await FirstAsync();
    return await SecondAwait(intermediate);
    

    For more on async performance, see Stephen Toub's MSDN article and video on the topic.

    Update: I've written a blog post that goes into much more detail.

提交回复
热议问题