开发者

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 rath开发者_如何学运维er 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.


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.


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


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜