我是否必须在Web API REST方法中添加显式线程? [英] Must I add explicit threading to my Web API REST methods?
问题描述
我已经创建了一些Web API REST方法,这些方法将由手持设备/Windows CE客户端调用.因此,服务器可能同时受到多个请求的攻击(嗯,会更像是它,问题是多少).
I have created some Web API REST methods that will be called by handheld/Windows CE clients. So the server may be hit by multiple (well, will be is more like it, the question being how many) requests simultaneously.
REST方法会自动解决此问题,还是我必须显式添加线程代码,以便一个客户端的请求不会干扰另一个客户端的请求?
Do the REST methods automatically take care of this, or do I have to explicitly add threading code so that one client's request does not interfere with anothers?
推荐答案
不需要-asp.net框架已经汇集了多个线程,可以同时处理多个请求.
No need - the asp.net framework already pools a number of threads for handling a number of requests concurrently.
传入请求入队,池线程轮流将请求出队并处理.
Incoming requests are enqueued, and pooled threads take their turn at dequeuing requests and handling them.
您可以在此处找到有关asp.net如何处理此问题的更多信息: http://www.codeproject.com/Articles/38501/Multi-Threading-in-ASP-NET
You can find more about how asp.net handles this here: http://www.codeproject.com/Articles/38501/Multi-Threading-in-ASP-NET
修改
但是,您应该将CPU/IO密集型工作负荷推迟到其他线程(最好使用TPL),以便由asp.net管理的线程保持响应状态.
You should, however, defer CPU/IO-intensive workloads to other threads (preferably using TPL), so that the threads managed by asp.net remain responsive.
警告:如果在处理请求时确实产生了新线程,请确保在从"REST方法"返回之前,它们均已完成.您可能会想:我将尽快回到用户手中,并在后台保留一个线程,将东西保存到数据库中."这很危险,主要是因为应用程序池可能被回收,从而中止了后台线程.在此处阅读更多信息:
Warning: if you do spawn new threads while handling a request, make sure they have all finished before returning from the "REST method". You may think "I'm gonna return to the user asap, and leave a thread in the background saving stuff to the database." This is dangerous, mainly because the Application Pool may be recycled, aborting your background threads. Read more here: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx
在所有线程完成之前不要返回.
Do not return until all threads have finished.
这篇关于我是否必须在Web API REST方法中添加显式线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!