async/await - when to return a Task vs void?

后端 未结 7 1157
梦如初夏
梦如初夏 2020-11-21 23:47

Under what scenarios would one want to use

public async Task AsyncMethod(int num)

instead of

public async void AsyncMetho         


        
7条回答
  •  借酒劲吻你
    2020-11-22 00:14

    The problem with calling async void is that

    you don’t even get the task back. You have no way of knowing when the function’s task has completed. —— Crash course in async and await | The Old New Thing

    Here are the three ways to call an async function:

    async Task SomethingAsync() { ... return t; }
    async Task SomethingAsync() { ... }
    async void SomethingAsync() { ... }
    

    In all the cases, the function is transformed into a chain of tasks. The difference is what the function returns.

    In the first case, the function returns a task that eventually produces the t.

    In the second case, the function returns a task which has no product, but you can still await on it to know when it has run to completion.

    The third case is the nasty one. The third case is like the second case, except that you don't even get the task back. You have no way of knowing when the function's task has completed.

    The async void case is a "fire and forget": You start the task chain, but you don't care about when it's finished. When the function returns, all you know is that everything up to the first await has executed. Everything after the first await will run at some unspecified point in the future that you have no access to.

提交回复
热议问题