问题
The system I'm working on needs to consume an IEnumerable of work items, iterate through each of them, and in between them wait for a certain period of time. I would like to keep the system as simple as possible at the enumeration site. That is, I'd like to have a method that I can call at the end of the foreach block which will block for the specific amount of time I specify - but I don't want to use Thread.Sleep because it's impossible to guarantee precision.
The minimum amount of time I'll need to block for is 100ms, but I don't want it to block any longer than this, which I've seen Thread.Sleep do on occasion (I assume because of the time taken in context switches, etc).
Edit: Related; does a call to WaitHandle.Wait with a timeout value do the same thing as Thread.Sleep?
回答1:
Why exactly do you need to wait while enumarating?
If a IEnumerable collection changes while you're going through it you'll get an exception so as a matter of fact no items can be added or removed by other threads while you thread is working on it.
Given that, why the artificial delay? Just consume it as it comes and let the scheduler distribute the work among your threads.
If you want a really really precise wait time I suggest you use a Thread.Sleep(time - 20 ms) and then busy wait for the right time do your work.
Only real time operating system can give you such precision. You can assume Thread.Sleep has a precision of about 20 ms so you could, in theory sleep until the desired time - the actual time is about 20 ms and THEN spin for 20 ms but you'll have to waste those 20 ms. And even that doesn't guarantee that you'll get real time results, the scheduler might just take your thread out just when it was about to execute the RELEVANT part (just after spinning)
回答2:
Thread.Sleep() has an accuracy of approx 20ms, give or take. You won't be getting anything better without going to (unmanaged) multimedia timers. And since you are just pausing a liitle that seems overkill. Try Sleep(80).
Additional: all timeout values have, as far as I know, the same resolution as Sleep().
来源:https://stackoverflow.com/questions/1322593/what-is-a-precise-way-to-block-a-thread-for-a-specific-period-of-time