.NET Thread.Sleep() is randomly imprecise

前端 未结 7 1891
故里飘歌
故里飘歌 2021-01-20 01:34

In my .NET application I have to replay a series of sensor events. So I created a thread that fires these events (usually about every 1 - 4 millisecond). I implemented a loo

7条回答
  •  有刺的猬
    2021-01-20 02:15

    Thread.Sleep really just calls win32 Sleep function, whose documentation details the inaccuracy.

    What Thread.Sleep really does is give up control for about the specified milliseconds. The Sleep function details that could be more or less. The rate at which the OS can give back control is determined by the system quantum, which is 10-15 milliseconds. So, in reality Thread.Sleep can only be accurate to the nearest quantum. But, as others have pointed out, if the CPU is under heavy load that, time will be longer. Plus, if your thread has a lower priority than all other threads, it may not get time.

    In terms of load, it's about load when the switch might occur. You're talking about a 1ms timeout (which is really about 15, as you've witnessed, due to the system quantum or timer accuracy) which means that the OS really only needs to be busy for 15-30 ms before it can be too busy to give back control to a thread until a future quanta. That's not a whole lot of time. If something of higher priority needs CPU in that 15-40ms, the higher-priority threads gets the time-slice, potentially starving the thread that gave up its control.

    What Thread.Sleep really means (for timeout values larger than 1) is that it's telling the OS that this thread is lower in priority than every other thread in the system for at least the timeout value, until the thread gets control back. Thread.Sleep is not a timing mechanism, it's a means of relinquishing control. They should really rename "Sleep" to "Yield".

    If you want to design something that periodically does something, use a timer. If you need to be really precise, use a multimedia timer.

提交回复
热议问题