Search code examples
.netthread-sleep

Does Threading.Thread.Sleep accepts ticks?


When using Threading.Thread.Sleep in .NET, there is an option to use Threading.Thread.Sleep(timeout As TimeSpan). Now, in System.TimeSpan there is the option to express period in 100-nanosecond units: System.TimeSpan(ticks as long). Can Threading.Thread.Sleep work with nanoseconds or it converts them to milliseconds (integer)? If it converts them to milliseconds I quess there is no way to suspend a thread for less than 1 millisecond. Is that right?


Solution

  • That falls in the "it depends" category. You could, say, be using it in a Silverlight app that runs on a Mac. But a standard Windows desktop app uses the operating system's Sleep() call which accepts a sleep time expressed only in milliseconds.

    That's not where it ends, by default Windows can only sleep a thread with an accuracy that depends on the operating system clock interrupt. Which is, by default, 1/64 of a second, 0.015625 seconds on most machines. So if you Thread.Sleep(1) then you'll actually sleep for about 16 milliseconds. Or more.

    You can jack up the interrupt rate by pinvoking timeBeginPeriod(1). Sleeps are now accurate to a millisecond, plus or minus a bunch due to scheduling inaccuracies. Something you should never do on a battery-powered machine. And don't forget to pinvoke timeEndPeriod().