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

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

    If you won't use return await you could ruin your stack trace while debugging or when it's printed in the logs on exceptions.

    When you return the task, the method fulfilled its purpose and it's out of the call stack. When you use return await you're leaving it in the call stack.

    For example:

    Call stack when using await: A awaiting the task from B => B awaiting the task from C

    Call stack when not using await: A awaiting the task from C, which B has returned.

提交回复
热议问题