Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a simple alternative to Thread.Sleep

Tags:

c#

sleep

HI,

During the development of my app, I was using Thread.Sleep to give our external devices some time to adjust to settings before making queries, as they are quite old and slow.

I now want to replace these with something a bit more stylish and correct.

Does anyone have a simple way to "wait" for a device rather than sleep, bearing in mind the device does not let us know when it is ready, so a wait is about as good as we can do !??

Regards, George.

like image 415
George Avatar asked May 17 '10 08:05

George


People also ask

What we can use instead of thread sleep?

Java static code analysis: "wait(...)" should be used instead of "Thread. sleep(...)" when a lock is held.

What can we use instead of thread sleep in Java?

TimeUnit provides a human-readable version of the Thread. sleep() method which can be used in place of the former. For a long time Thread's sleep() method is a standard way to pause a Thread in Java and almost every Java programmer is familiar with that.

Why thread sleep is not recommended?

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

How do I make thread sleep for a minute?

To make a thread sleep for 1 minute, you do something like this: TimeUnit. MINUTES. sleep(1);


1 Answers

It may be a better fit to go down the route of using a timer to periodically wake up and see if the device is ready.

You have at least two options here System.Timers.Timer or System.Threading.Timer.

However, this would probably mean you'd have to get more involved in multithreading in order that the timer can notify the rest of your program to continue when the device is ready (e.g. using a WaitHandle or some sort, such as an AutoResetEvent).

There isn't anything intrinsically wrong with using Thread.Sleep to block a single synchronous thread IMHO.

like image 123
Rob Levine Avatar answered Sep 21 '22 17:09

Rob Levine