Must I add explicit threading to my Web API REST methods?

微笑、不失礼 提交于 2019-12-23 11:13:09

问题


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.

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?


回答1:


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.

You can find more about how asp.net handles this here: http://www.codeproject.com/Articles/38501/Multi-Threading-in-ASP-NET

Edit

You should, however, defer CPU/IO-intensive workloads to other threads (preferably using TPL), so that the threads managed by asp.net remain responsive.

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.




回答2:


As dcastro said, normally you don't need to worry about requests interfering with each other.

However, if you are using things like global variables or single instance classes then it is likely that you will have threading issues. Just stay away from that stuff and you'll be fine.



来源:https://stackoverflow.com/questions/20230093/must-i-add-explicit-threading-to-my-web-api-rest-methods

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