Await on the last method line

那年仲夏 提交于 2019-12-03 11:21:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10247258/await-on-the-last-method-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!