mattias mattias - 2 months ago 24x
C# Question

await vs await c#

I've searched the web and seen alot of questions regarding vs await async but there is this specific usage scenario where I don't not really understand the difference. Scenario is quite simple i believe.

await Task.Run(() => LongProcess());


await LongProcess());

where LongProcess is a async method with a few asynchronous calls in it like calling db with await ExecuteReaderAsync() for instance.


Is there any difference between the two in this scenario? Any help or input appreciated, thanks!


Task.Run may post the operation to be processed at a different thread. That's the only difference.

This may be of use - for example, if LongProcess isn't truly asynchronous, it will make the caller return faster. But for a truly asynchronous method, there's no point in using Task.Run, and it may result in unnecessary waste.

Be careful, though, because the behaviour of Task.Run will change based on overload resolution. In your example, the Func<Task> overload will be chosen, which will (correctly) wait for LongProcess to finish. However, if a non-task-returning delegate was used, Task.Run will only wait for execution up to the first await (note that this is how TaskFactory.StartNew will always behave, so don't use that).