且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我是否必须在Web API REST方法中添加显式线程?

更新时间:2023-02-14 19:54:08

不需要-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.