Why Thread.Sleep waits longer than requested when other apps are running?

后端 未结 5 473
既然无缘
既然无缘 2020-12-07 02:53

I have a small problem regarding threading in C#. For some reason, my thread speeds up from 32ms delay to 16ms delay when I open Chrome, when I close Chrome it goes back to

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 03:22

    First, 1000 / 60 = 16 ms

    The PC clock has a resolution of around 18-20ms, Sleep() and the result of DateTime.Now will be rounded to a multiple of that value.

    So, Thread.Sleep(5) and Thread.Sleep(15) will delay for the same amount of time. And that can be 20, 40 or even 60 ms. You do not get much guarantees, the argument for Sleep() is only a minimum.

    And another process (Chrome) that hogs the CPU (even a little) can influence the behavior of your program that way. Edit: that is the reverse of what you're seeing, so something a little else is happening here. Still, it's about rounding to timeslices.

提交回复
热议问题