Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it sane to use Thread.Sleep(int) in ASP.NET or should I use another method?

I want to introduce a slight wait during some testing functions, to simulate a server call. Is it sane to use Thread.Sleep(int) to introduce the wait or is there a better method to have the server wait?

Note, I'll be pausing long enough for me to visually see a sufficient lag, even tho I don't expect to see such a delay in the actual app. This is for me to visualize the actual delay that could occur.

I plan on running this both in the VS2010 local debugger webserver and in IIS 7. I'm on .NET 3.5

like image 235
jcolebrand Avatar asked Mar 16 '11 21:03

jcolebrand


People also ask

Why thread sleep is not recommended?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

Is Task delay the same as thread sleep?

sleep will block a thread and task. delay will not and has a cancellation token, unless your app is pretty complex, it really doesn't matter as on the surface: task. delay and thread. sleep do pretty much the same thing.

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.

Does thread sleep block other threads?

Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution. One thread cannot call Thread. Sleep on another thread.


2 Answers

Thread.Sleep(int) is what I would use.

like image 117
The Muffin Man Avatar answered Oct 03 '22 16:10

The Muffin Man


If you're using MVC and SessionState your requests will be automatially serialized - so if you're checking for race conditions with a random Thread.Sleep() value then Request B will never complete before Request A even if the time slept if less.

ASP.NET MVC and Ajax, concurrent requests?

like image 27
Simon_Weaver Avatar answered Oct 03 '22 16:10

Simon_Weaver