Search code examples
c#multithreadingdoublesleepmilliseconds

How to get similar result as if Thread.Sleep were supports double values?


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.


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