I've recently come across this code in a WinForm application and I can't figure if there is any reason to run async
code inside a Task.Run
that is awaited.
public async Task SaveStuff()
{
await Task.Run(() => SaveStuffAsync().ConfigureAwait(false));
await Task.Run(() => SendToExternalApiAsync().ConfigureAwait(false));
}
private async Task SaveStuffAsync()
{
await DbContext.SaveChangesAsync().ConfigureAwait(false);
}
private async Task SendToExternalApiAsync()
{
// some async code that is awaited with ConfigureAwait(false);
}
Wouldn't this code do the exact same thing without the Task.Run?
public async Task SaveStuff()
{
await SaveStuffAsync().ConfigureAwait(false);
await SendToExternalApiAsync().ConfigureAwait(false);
}
SaveStuffAsync
may block the calling thread despite the fact that it is declared as an async method. Calling it on a thread pool thread makes sure that your UI won't freeze regardless of the actual implementation of the (potentially) async method.Task.Run()
, an async method viaTask.Run()
, and awaiting an async method directly. So...all of them.