Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "return await" in C#?

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?

like image 346
TX_ Avatar asked Sep 30 '13 15:09

TX_


People also ask

What is await return C?

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.

Should we use await in return?

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 .

What is the return type of 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.

What is the purpose of await keyword?

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.


1 Answers

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.

like image 187
svick Avatar answered Oct 12 '22 16:10

svick