在asp.net中的thread.sleep [英] thread.sleep in asp.net

查看:54
本文介绍了在asp.net中的thread.sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为自己的站点模拟彗星实时供稿协议,因此在我的控制器中添加:

while(nothing_new && before_timeout){
  Thread.Sleep(1000);
}

但是我发现添加此功能后,整个网站变慢了.调试后,我得出的结论是,当我调用Thread.Sleep时,所有线程,即使在其他请求中也都被阻塞.

为什么Thread.Sleep阻止所有线程,而不仅仅是当前线程,我应该如何处理这样的问题?

解决方案

@Servy所说的正确.除了他的回答外,我还想投我2美分.我敢打赌,您正在使用ASP.NET会话,并且您正在从同一会话发送并行请求(例如,您正在发送多个AJAX请求).除了ASP.NET会话不是线程安全的,并且您不能有来自同一会话的并行请求. ASP.NET将简单地序列化调用并按顺序执行.

这就是为什么您正在观察此阻止的原因.它将仅阻止来自同一ASP.NET会话的请求.如果您从其他会话发送HTTP请求,它将不会被阻止.此行为是设计使然,您可以 here 了解更多信息.. >

ASP.NET会话就像癌症,我建议您一发现它们在Web应用程序中正在使用,就立即将它们禁用:

<sessionState mode="Off" />

不再排队.现在您有了一个可扩展的应用程序.

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.

Why does Thread.Sleep block all threads, not just the current thread, and how should I deal with an issue like this?

解决方案

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.

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 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:

<sessionState mode="Off" />

No more queuing. Now you've got a scalable application.

这篇关于在asp.net中的thread.sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆