C# asp.net中的thread.sleep
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15767081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
thread.sleep in asp.net
提问by Hilmi
I'm simulating the comet live feed protocol for my site, so in my controller I'm adding:
我正在为我的站点模拟彗星实时馈送协议,因此在我的控制器中我添加:
while(nothing_new && before_timeout){
Thread.Sleep(1000);
}
But I noticed the whole website got slow after I added this feature. After debugging I concluded that when I call Thread.Sleep
all the threads, even in other requests, are being blocked.
但是我注意到添加此功能后整个网站都变慢了。调试后我得出结论,当我调用Thread.Sleep
所有线程时,即使在其他请求中,也被阻塞。
Why does Thread.Sleep
block all threads, not just the current thread, and how should I deal with an issue like this?
为什么会Thread.Sleep
阻塞所有线程,而不仅仅是当前线程,这样的问题应该如何处理?
采纳答案by Darin Dimitrov
What @Servy said is correct. In addition to his answer I would like to throw my 2 cents. I bet you are using ASP.NET Sessions and you are sending parallel requests from the same session (for example you are sending multiple AJAX requests). Except that the ASP.NET Session is not thread safe and you cannot have parallel requests from the same session. ASP.NET will simply serialize the calls and execute them sequentially.
@Servy 说的是正确的。除了他的回答,我还想扔掉我的 2 美分。我敢打赌,您正在使用 ASP.NET 会话,并且您正在从同一会话发送并行请求(例如,您正在发送多个 AJAX 请求)。除了 ASP.NET 会话不是线程安全的,并且您不能从同一会话中获得并行请求。ASP.NET 将简单地序列化调用并按顺序执行它们。
That's why you are observing this blocking. It will block only requests from the same ASP.NET Session. If you send an HTTP requests from a different session it won't block. This behavior is by design and you can read more about it here
.
这就是为什么您要观察这种阻塞。它只会阻止来自同一个 ASP.NET 会话的请求。如果您从不同的会话发送 HTTP 请求,它不会阻止。此行为是设计使然,您可以阅读有关它的更多信息here
。
ASP.NET Sessions are like a cancer and I recommend you disabling them as soon as you find out that they are being used in a web application:
ASP.NET 会话就像癌症一样,我建议您在发现它们正在 Web 应用程序中使用时立即禁用它们:
<sessionState mode="Off" />
No more queuing. Now you've got a scalable application.
不用排队了。现在您有了一个可扩展的应用程序。
回答by Servy
I concluded that when I call thread.sleep all the threads even in other requests are being blocked
我得出的结论是,当我调用 thread.sleep 时,即使在其他请求中,所有线程都被阻塞
That conclusion is incorrect. Thread.Sleep
does not block any other thread, it only blocks the current thread. If multiple threads are all being blocked by this line of code then it is because all of those threads are hitting this line of code.
这个结论是错误的。 Thread.Sleep
不阻塞任何其他线程,它只阻塞当前线程。如果多个线程都被这行代码阻塞,那是因为所有这些线程都在访问这行代码。