Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to Thread.Sleep() for simulating pauses

Tags:

So Thread.Sleep() is bad (http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx).

Is there any recommended alternative to simulating a pause in execution of a program? Eg a loop? Although I suppose this involves a lot of overhead in initialising variables, checking the bool condition, etc.

Thanks

like image 234
GurdeepS Avatar asked Sep 21 '09 22:09

GurdeepS


People also ask

What can I use instead of sleep in Java?

For your case I would suggest a spinning loop instead.

Can you pause a thread in C#?

To pause a thread in C#, use the sleep() method.


2 Answers

If you are only going to simulate a pause (as in for test purposes), I think Thread.Sleep is a perfectly valid approach. On the other hand, if you are actually waiting for something, some sort of thread-safe signalling mechanism would be better (check the types that inherits WaitHandle).

like image 134
Fredrik Mörk Avatar answered Oct 04 '22 14:10

Fredrik Mörk


simulating a pause

"Simulating" sounds like something you would only do in debugging. Thread.Sleep should be fine.

The main problem with Sleep is that usually you should be waiting for something specific to occur rather than waiting for an arbitrary delay.

The other thing to watch out for is calling Thread.Sleep from a UI thread, which will make the UI unresponsive. Better to disable the parts of the UI that you do not want the user to interact with and then use a Timer control to implement the delay.

like image 34
Jason Kresowaty Avatar answered Oct 04 '22 15:10

Jason Kresowaty