简体   繁体   中英

C# Will code execution continue after await?

After a lot of readings about await/async, I still have some misunderstanding about the subject. Please provide a short answer (yes/no) and a long answer to my questions, so I can have better understanding.

Let's say we have the following method:

public async Task UnresultTaskMethod()
{
   await AsyncMethod1();
   await AsyncMethod2();
}

Questions:

  1. When the execution of the code will reach AsyncMethod1 , will it automatically move to call AsyncMethod2 while AsyncMethod1() is getting executed?
  2. When the execution of the code will reach AsyncMethod2 , will the execution of the method ends, and the execution will return to the caller, before the execution of AsyncMethod2 completely ends?
  3. Is there such a cases where the execution of the method will end before the calls to async method fully completes (for example the method was void instead of task)?
  4. When I will need to put Task.WaitAll(tasks); Task.WhenAll(tasks); Task.WaitAll(tasks); Task.WhenAll(tasks); at the end so I can make sure the execution will not continue before all the tasks have ended, this is the main factor of confusion for me, why to wait for a task in this way if you can wait for them by keyword await?
  5. I was thinking when the execution will hit async method with await, it will put it on processing schedule, and continue to execute the code inside the function, I'm feeling that I misunderstood.

await roughly means 'wait until completed'

  1. No

  2. No

  3. If you don't await, it might be the case, for example

public async Task UnresultTaskMethod()
{
   Task.Delay(2000);

   // We haven't awaited, so we're here right away
   await AsyncMethod2();
}
  1. Task.WaitAll and Task.WhenAll don't make sense when you await individual tasks right away. However, you can do this:
public async Task UnresultTaskMethod()
{ 
   var task1 = AsyncMethod1();
   var task2 = AsyncMethod2();

   // The tasks are now doing their job

   await Task.WhenAll(task1, task2);
 
   // Here you are sure both task1 and task2 are completed
}

With Task.WaitAll it would be like this:

public async Task UnresultTaskMethod()
{ 
   var task1 = AsyncMethod1();
   var task2 = AsyncMethod2();

   // This is not awaitable, you're blocking the current thread
   Task.WaitAll(task1, task2);
 
   // Here you are sure both task1 and task2 are completed
}

In this case, you don't need async Task , because you are not awaiting, ie it is effectively a void method.

  1. Hopefully now it is a bit clearer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM