Any difference between “await Task.Run(); return;” and “return Task.Run()”?

后端 未结 4 1124
日久生厌
日久生厌 2020-11-22 01:59

Is there any conceptual difference between the following two pieces of code:

async Task TestAsync() 
{
    await Task.Run(() => DoSomeWork());
}
         


        
4条回答
  •  终归单人心
    2020-11-22 02:56

    The two examples do differ. When a method is marked with the async keyword, the compiler generates a state-machine behind the scenes. This is what is responsible for resuming continuations once an awaitable has been awaited.

    In contrast, when a method is not marked with async you are losing the ability to await awaitables. (That is, within the method itself; the method can still be awaited by its caller.) However, by avoiding the async keyword, you are no longer generating the state-machine, which can add a fair bit of overhead (lifting locals to fields of the state-machine, additional objects to the GC).

    In examples like this, if you are able to avoid async-await and return an awaitable directly, it should be done to improve the efficiency of the method.

    See this question and this answer which are very similar to your question and this answer.

提交回复
热议问题