Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread.sleep in asp.net

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?

like image 715
Hilmi Avatar asked Apr 02 '13 14:04

Hilmi


People also ask

What is thread sleep?

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.

What is the use of thread sleep in C#?

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)

How long is thread sleep 1000?

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.

What is the difference between thread sleep and wait?

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.


1 Answers

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.

like image 106
Darin Dimitrov Avatar answered Sep 17 '22 14:09

Darin Dimitrov