George
George

Reputation: 407

Looking for a simple alternative to Thread.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.

Upvotes: 7

Views: 5341

Answers (4)

Rob Levine
Rob Levine

Reputation: 41298

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.

Upvotes: 7

allonym
allonym

Reputation: 1418

I prefer to use Monitor.Wait over Thread.Sleep in most cases, because unlike Thread.Sleep it can be unblocked with Monitor.Pulse if need be. For a good explanation of why Thread.Sleep should be used judiciously, see http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062512

As long as you are doing the calls from a background thread, that probably isn't a terrible way to do it. You could also use a timer to call-back after an interval; more ecomplex (not much), but perhaps easier to cancel (of course, you can also simply handle a thread-interrupt to cancel a sleep).

Upvotes: 1

David Neale
David Neale

Reputation: 17018

The best way to make an application wait is to use Thread.Sleep()

Of course, you have a real problem where you're needing to select an arbituary timescale to wait for the device to update.

Is there no way that you app can try to carry on and retry if it fails due to the device's state? (Of course there would need to be a max. no. of retries)

Upvotes: 1

Related Questions