If I have the following method:
public async Task<T> DoSomethingAsync<T>(Func<Task<T>> action)
{
// bunch of async code..then "await action()"
}
What is the difference between the following two usages:
public async Task MethodOneAsync()
{
return await DoSomethingAsync(async () => await SomeActionAsync());
}
public async Task MethodTwoAsync()
{
return await DoSomethingAsync(() => SomeActionAsync());
}
Both compile, both work and there are no C# warnings.
What's the difference (if any)? Will both methods run true async if awaited by the caller?
There is no functional difference between the two. The only difference is if the Task
from SomeActionAsync is returned directly or if it is awaited. Stephen Cleary has a good blog post about this, and recommends the second aproach for this trivial case.
The reason why the first approach is available is that you could have a non-trivial lambda expression like this:
public async Task MethodOneAsync()
{
return await DoSomethingAsync(async () => {
var i = _isItSunday ? 42 : 11;
var someResult = await SomeActionAsync(i);
return await AnotherActionAsync(someResult*i);
});
}
So the difference is the same as the difference between a method whith this signature public async Task<int> MyMethod
and this one public Task<int> MyMethod
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With