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?
Syntax in c language: If only one child process is terminated, then return a wait() returns process ID of the terminated child process. If more than one child processes are terminated than wait() reap any arbitrarily child and return a process ID of that child process.
However, if you want to catch the rejected promise you're returning from an asynchronous function, then you should definitely use return await promise expression and add deliberately the await .
Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression.
The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.
There is one sneaky case when return
in normal method and return await
in async
method behave differently: when combined with using
(or, more generally, any return await
in a try
block).
Consider these two versions of a method:
Task<SomeResult> DoSomethingAsync() { using (var foo = new Foo()) { return foo.DoAnotherThingAsync(); } } async Task<SomeResult> DoSomethingAsync() { using (var foo = new Foo()) { return await foo.DoAnotherThingAsync(); } }
The first method will Dispose()
the Foo
object as soon as the DoAnotherThingAsync()
method returns, which is likely long before it actually completes. This means the first version is probably buggy (because Foo
is disposed too soon), while the second version will work fine.
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