views:

122

answers:

1

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?

+2  A: 

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)

Jorge Córdoba
"active wait" ?
Erik Forbes
Btw - I really really do want what I'm asking for. =)
Erik Forbes
You never know :) Active wait is a very bad translation of "espera activa" which is how is known in Spanish :P ... Corrected to "Busy Wait"
Jorge Córdoba
No I understood the concept - I was hoping for a little more detail. =) How would I active wait without cooking the processor for those extra ~20-40 ms?
Erik Forbes
You can't, 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)
Jorge Córdoba
Ah, I see. Alas - that's what I thought. Ah well - thanks a lot for your help and input. =)
Erik Forbes