ApiController中的Async和Await发布 [英] Async and Await in ApiController Post
问题描述
关于.net 4.5中的异步和等待,我还是不太清楚.到目前为止,我想我知道这一切正在等待:
I'm still not quite clear about async and await in .net 4.5. So far, I think I understand that await:
- 将功能(在右侧)放在单独的线程上.
- 将执行返回给当前函数的调用者
- 但是保留当前函数的其余代码人质",直到等待(异步)函数完成.
如果我误会了什么,请纠正我.因此,如果以上都是正确的话,那么我就想使用ApiController的Post函数进行异步处理:
Please correct me if I'm misunderstanding something. So, if the above is true, I'm stuck with an ApiController's Post function that I want async:
[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]MyObject obj)
{
myDataContext.MyObjects.InsertOnSubmit(obj);
myDataContext.SubmitChanges();
await SomeReallyLongRunningTaskAsync();
// obj would now have the new Id, which I'm really after.
return Request.CreateResponse(HttpStatusCode.Created, obj);
}
因此,如果我正确理解这一点,则Post将完成执行并将控制权返回给任何称为myApiController.Post(obj)
的人.但是自从等待return Request.CreateResponse(HttpStatusCode.Created, obj);
人质"以来,我还没有HttpResponseMessage
对象.
So if I'm understanding this correctly, Post will finish execution and return control to whoever called myApiController.Post(obj)
. But I don't have the HttpResponseMessage
object yet since await held return Request.CreateResponse(HttpStatusCode.Created, obj);
"hostage".
在上面的简单示例中,调用会立即返回到客户端(即客户端JS网站或移动应用程序)吗?如果是这样,那是201、400、500(最好不是)吗?
In this above simple example, would the call immediately return to the client (that is, client JS website or mobile app)? If so, would it be a 201, 400, 500 (better not), others?
推荐答案
除了斯蒂芬的回答,我还需要指出一些事情.
In addition to Stephen's answer I need to point out a few things.
首先,控制器中的异步不会使用户体验异步.只要SomeReallyLongRunningTaskAsync()
需要,用户就必须等待. [所以我们为什么要异步?见下一点]
First, async in the controller does not make the user experience async. User will have to wait as long as SomeReallyLongRunningTaskAsync()
takes. [So why do we do async? See the next point]
此外,如果SomeReallyLongRunningTaskAsync()
受CPU限制,则不应在异步模式下调用它. 在服务器场景中使用异步的主要原因是释放CLR线程回到池中,以便 IO完成端口(IOCP)可以处理其余部分-直到完成IO工作,然后再回到线程池.这样可以避免在ASP.NET方案中常见的线程不足问题.
Also, if the SomeReallyLongRunningTaskAsync()
is CPU-bound, then you should not call it in async mode. The main reason to use Async in a server scenario is to release the CLR thread back to the pool so that the IO Completion Port (IOCP) can handle the rest - until IO work done which then goes back to the thread pool. This will prevent the problem of Thread Starvation which is common in ASP.NET Scenarios.
仅在 IO受限情况下使用 的IOCP,例如:
IOCPs are used ONLY in IO-bound situations, examples are:
- 读取/写入文件
- 访问数据库或
- 访问外部Web服务或WCF服务
在线提供了大量资源,并解释了各个方面.如果我可以插上插头,请本书的第二章是一个很好的资源,可以使人们对Web API中的Async产生连贯的了解.
There are tons of resources available online and explain various aspects. If I may put a plug, Chapter 2 of this book is an excellent resource which gives a cohesive understanding of Async in Web API.
这篇关于ApiController中的Async和Await发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!