Awaiting tasks: Return task or await if no code after await [duplicate]

纵然是瞬间 提交于 2019-12-18 03:12:47

问题


I've done a bit of reading, and think I have grasped the basics of the await and async keywords, with regards to System.Threading.Task.

I'm not sure if I'm right over a small issue, however, and am looking for verification or for someone to correct me.

I'm implementing an async method, with this signature:

public Task ProcessUploadedFile(FileInfo info, string contentType);

Obviously, if I want to await anything inside the method, I need to add the async keyword into the signature,

My question is this: If the last thing that my method does is call another async method, or return a task, is there any point in awaiting it?

Eg.

1:

public async Task ProcessUploadedFile(FileInfo info, string contentType)
{
  foreach (var something in someCollection)
    DoSomething();

  DoSomethingElse();

  await DoMethodAsync();
}

2:

public Task ProcessUploadedFile(FileInfo info, string contentType)
    {
      foreach (var something in someCollection)
        DoSomething();

      DoSomethingElse();

      return DoMethodAsync();
    }

I initially wrote the former, but can no longer see the point in adding the await. If I were to write the latter, I accomplish the same thing, and the caller of both methods can still use the await keyword if they choose, no?

Is there any difference in the above? Which is "better"?


回答1:


await is used to continue execution of method body when awaiting completed. If there is nothing to continue, then you don't need awaiting.

You can think of await (simplified) as of ContinueWith operation. So, your first method is something like:

foreach (var something in someCollection)
     DoSomething();

DoSomethingElse();

DoMethodAsync().ContinueWith(t => {});

There is nice MSDN article which describes what happens in async method which has nice code flow picture:



来源:https://stackoverflow.com/questions/18061849/awaiting-tasks-return-task-or-await-if-no-code-after-await

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