Could someone please let me know when do we use one over the other with the below two implementations:
await Task.Run(async () => Method());
await Task.Run(() => Method());
What is the purpose for using async
within the Task.Run()
call?
Could someone please let me know when do we use one over the other with the below two implementations:
await Task.Run(async () => Method());
await Task.Run(() => Method());
What is the purpose for using async
within the Task.Run()
call?
There is no real reason to use #1. The point of using Task.Run
is to make a long running task or I/O intensive unit of work and make it asynchronous, and since #1 is already asynchronous, the async anonymous function inside of the Task.Run
is redundant and unnecessary.
Either you do the following to convert a unit of work to asynchronous:
await Task.Run(() => Method());
public void Method()
{
//doing intensive work here
}
Or you just await
the already asynchronous unit of work.
await MethodAsync();
public async Task MethodAsync()
{
//doing async work here
}
If the method you are calling is async you can use the async/await in the function.
async Task MainAsync()
{
await Task.Run(async () => await MethodAsync());
await Task.Run(() => Method());
}
async Task MethodAsync() { ... }
void Method() { ... }