C# await / async in WebApi, what's the point?

狂风中的少年 提交于 2019-12-10 13:15:08

问题


Does anybody know what is the purpose of doing this?

 private async Task<bool> StoreAsync(TriviaAnswer answer) { ... }

 [ResponseType(typeof(TriviaAnswer))]
 public async Task<IHttpActionResult> Post(TriviaAnswer answer)
 {
     var isCorrect = await StoreAsync(answer);
     return Ok<bool>(isCorrect);
 }

From examining this, it is telling it to run the private method asynchronously but synchronously wait for it to end. My question is, is there any point to this? Or is this just a fancy yet futile technique? I ran into this while studying some code for Web API / MVC / SPA.

Anyway, any insights would be useful.


回答1:


Despite its name, await doesn't actually work like Thread.Join. async and await are Microsoft's implementation of coroutines, implemented using a Continuation Passing Style. Work is reordered so that processing can continue while the Task<T> is being completed. Instructions are re-arranged by the compiler to make maximum use of the asynchronous operation.

This article explains it thusly:

An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

For some trivial code examples, await doesn't really make much sense, because there is no other work that you can do in the meantime while you are awaiting.



来源:https://stackoverflow.com/questions/25716366/c-sharp-await-async-in-webapi-whats-the-point

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