Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await on the last method line

Still learning about async-await. I bumped into examples similar to following:

public async Task MethodAsync()
{
  await Method01Async();
  await Method02Async();
}

What is the purpose of the last await? Method02Async is the last line of MethodAsync method. So there is no any method remainder - no any lines below - no anything to be called in the callback generated by the compiler... Am I missing anything?

like image 502
Hans Avatar asked Apr 20 '12 13:04

Hans


People also ask

Does await blocks the next line?

await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have an effect on it.

Does await pause execution?

The await expression causes async function execution to pause until a promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled promise.

What does await () do in Java?

The await() method of the Java CyclicBarrier class is used to make the current thread waiting until all the parties have invoked await() method on this barrier or the specified waiting time elapses.

How do you call await method?

You read the 'await' keyword as "start this long running task, then return control to the calling method". Once the long-running task is done, then it executes the code after it. The code after the await is similar to what used to be CallBack methods.


1 Answers

There actually is a "method remainder" - it completes the Task returned by MethodAsync.

(The return value of) Method02Async is awaited so that MethodAsync is not completed until Method02Async completes.

If you had:

public async Task MethodAsync()
{
  await Method01Async();
  Method02Async();
}

Then the MethodAsync will (asynchronously) wait for Method01Async to complete and then start Method02Async. MethodAsync will then complete while Method02Async may still be in progress.

The way you have it:

public async Task MethodAsync()
{
  await Method01Async();
  await Method02Async();
}

Means that MethodAsync will (asynchronously) wait for Method01Async to complete and then (asynchronously) wait for Method02Async to complete, and only then will MethodAsync complete.

like image 106
Stephen Cleary Avatar answered Sep 20 '22 16:09

Stephen Cleary