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?
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
In C#, a Sleep() method temporarily suspends the current execution of the thread for specified milliseconds, so that other threads can get the chance to start the execution, or may get the CPU for execution. There are two methods in the overload list of Thread. Sleep Method as follows: Sleep(Int32)
sleep time means more than what you really intended. For example, with thread. sleep(1000), you intended 1,000 milliseconds, but it could potentially sleep for more than 1,000 milliseconds too as it waits for its turn in the scheduler. Each thread has its own use of CPU and virtual memory.
Sleep() method belongs to Thread class. Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With