Is there any scenario where writing method like this:
public async Task<SomeResult> DoSomethingAsync()
{
// Some synchronous code might or might not be here... //
return await DoAnotherThingAsync();
}
instead of this:
public Task<SomeResult> DoSomethingAsync()
{
// Some synchronous code might or might not be here... //
return DoAnotherThingAsync();
}
would make sense?
Why use return await
construct when you can directly return Task<T>
from the inner DoAnotherThingAsync()
invocation?
I see code with return await
in so many places, I think I might have missed something. But as far as I understand, not using async/await keywords in this case and directly returning the Task would be functionally equivalent. Why add additional overhead of additional await
layer?
Best Answer
There is one sneaky case when
return
in normal method andreturn await
inasync
method behave differently: when combined withusing
(or, more generally, anyreturn await
in atry
block).Consider these two versions of a method:
The first method will
Dispose()
theFoo
object as soon as theDoAnotherThingAsync()
method returns, which is likely long before it actually completes. This means the first version is probably buggy (becauseFoo
is disposed too soon), while the second version will work fine.