WebApi中的C#等待/异步,有什么意义? [英] C# await / async in WebApi, what's the point?

查看:142
本文介绍了WebApi中的C#等待/异步,有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道这样做的目的是什么吗?

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);
 }

通过检查,可以告诉它异步运行私有方法,但要同步等待它结束.我的问题是,这有什么意义吗?还是这只是一种幻想而又徒劳的技术?我在研究Web API/MVC/SPA的一些代码时遇到了这个问题.

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.

推荐答案

尽管它的名称是 await ,但它实际上并不像Thread.Join一样工作. async await 是Microsoft 协同程序,使用延续传递样式实现.重新安排工作的顺序,以便可以在完成 Task< T> 的同时继续进行处理.编译器会重新安排指令以最大程度地利用异步操作.

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.

本文对此进行了解释:

await表达式不会阻塞正在其执行的线程.相反,它使编译器将异步方法的其余部分注册为等待任务的延续.然后,控制权返回给异步方法的调用方.任务完成后,它将调用其继续,异步方法的执行将从中断的位置继续执行.

对于一些琐碎的代码示例, await 并没有多大意义,因为在等待期间,您没有其他可做的工作.

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.

这篇关于WebApi中的C#等待/异步,有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆