views:

427

answers:

4

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.

+1  A: 

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)

David Neale
+4  A: 

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.

Rob Levine
Well if u ask the device for info it simply gives u an ER error message, so I found just aiting was the best option.The whole ap has to wait for this device to respond anyway, so if Sleep() is not a bad practice, then I am happy to continue using it in single threads.Thanks all for the information, much appreciated.
George
I'd probably be inclined to leave it as-is too. You start adding complexity by having seperate timers that then have to signal to the rest of the program that the device is now ready.
Rob Levine
A: 

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).

Marc Gravell
A: 

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

allonym