Is there any conceptual difference between the following two pieces of code:
async Task TestAsync()
{
await Task.Run(() => DoSomeWork());
}
>
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.