0

在 .NET 中使用 Threading.Thread.Sleep 时,可以选择使用 Threading.Thread.Sleep(timeout As TimeSpan)。现在,在 System.TimeSpan 中,可以选择以 100 纳秒为单位表示周期:System.TimeSpan(ticks as long)。Threading.Thread.Sleep 可以使用纳秒还是将它们转换为毫秒(整数)?如果它将它们转换为毫秒,我认为没有办法将线程挂起少于 1 毫秒。那正确吗?

4

2 回答 2

2

您的假设是正确的,并记录在 MSDN 中:

这种睡眠过载使用超时的整毫秒总数。小数毫秒被丢弃。

我的理解是,由于多任务处理的性质,即使是毫秒值也不一定会产生非常精确的睡眠时间到毫秒。当我需要睡一段非常特定的时间时,我使用了这样的代码:

  long freq;
  long frame;
  freq = System.Diagnostics.Stopwatch.Frequency;
  frame = System.Diagnostics.Stopwatch.GetTimestamp();
  while ((frame - fpsStartTime) * fps < freq * fpsFrameCount)
  {
     int sleepTime = (int)((fpsStartTime * fps + freq * fpsFrameCount - frame * fps) * 1000 / (freq * fps));
     if (sleepTime > 0) System.Threading.Thread.Sleep(sleepTime);
     frame = System.Diagnostics.Stopwatch.GetTimestamp();
  }
  if (++fpsFrameCount > fps)
  {
     fpsFrameCount = 0;
     fpsStartTime = frame;
  }
于 2012-10-21T12:53:50.980 回答
2

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().

于 2012-10-21T15:11:26.473 回答