Question

Sometimes I need to sleep non integer amount of milliseconds, but can't find a way to do so. For example, if I want to sleep half of millisecond, I want to do this:

Thread.Sleep(0.5);

But can't, since Sleep supports integers only.

Was it helpful?

Solution

if your timings are so important than you are using entirely wrong tool for the job because

Thread.Sleep(n) means blocking the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more or than n milliseconds on different computers. The likelihood that your thread will re-awaken exactly after n milliseconds is about as impossible as impossible can be. So, Thread.Sleep is pointless for timing.

You can read all about this here.

Note: If you post the problem you are trying to address with

Thread.Sleep

we might be able to guide you in the right direction

OTHER TIPS

Thread.Sleep does not support non integer values for milliseconds because it does not have sub-millisecond resolution. In fact, the resolution is probably going to be much higher than 1 millisecond (probably 15ms or even higher depending on hardware). I suspect the API designers took that into account when deciding on the data type.

By the way, there two special cases.

Thread.Sleep(0) - This will cause the thread to yield to another thread with the same or higher priority.

Thread.Sleep(1) - This will cause the thread to yield to any thread regardless of priority.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top