.net thread.sleep 不准确
.net thread.sleep inaccurate
我快疯了!!
我通过 gsm 和语音规范发送音频,我必须发送语音数据包,然后等待 20 毫秒才能获得正常语音。我使用 system.threading.thread.sleep(20)。但是,我注意到声音很慢。但是当我 运行 另一个不同的应用程序时,声音变得正常。
经过一些调试,我发现 system.Threading.Thread.Sleep(20) 需要 31 毫秒,但如果我 运行 另一个不同的应用程序,Thread.Sleep (20) 将始终准确。
为了使线程准确休眠 20 毫秒并且同时不影响 PC 性能,我可以使用哪些其他替代方法。
谢谢,
Sleep(20)
表示睡眠至少20毫秒。基本上,它会挂起线程并且不会在指定的延迟内恢复调度。在那之后,线程仍然需要被调度才能真正恢复 运行。取决于其他线程 运行 可能立即或稍后。这里没有保证。
documentation 调用此:
The system clock ticks at a specific rate called the clock resolution.
The actual timeout might not be exactly the specified timeout, because
the specified timeout will be adjusted to coincide with clock ticks.
For more information on clock resolution and the waiting time, see the
Sleep function topic. This method calls the Sleep function from the
Windows system APIs.
如前所述,准确的计时通常需要一个不会被时间分割的thread/process,为此,您必须Spin
而不是Sleep
。
选项 1
如果你想要绝对的准确性而不是其他任何东西,我会使用带有秒表的专用高优先级线程。
bool running = true;
Thread t = new Thread(() =>
{
Stopwatch sw = Stopwatch.StartNew();
while (running)
{
if (sw.ElapsedMilliseconds >= 20)
{
RunCode();
sw.Restart();
}
}
}) { Priority = ThreadPriority.Highest, IsBackground = true };
t.Start();
// ...
running = false;
t.Join();
选项 2
瘦了一点,运行 不是在不同的线程上,但仍然旋转。
while (true)
{
SpinWait.SpinUntil(() => false, TimeSpan.FromMilliseconds(20));
RunCode();
}
选项 3
一些开源高分辨率定时器代码。例如https://gist.github.com/HakanL/4669495
我快疯了!! 我通过 gsm 和语音规范发送音频,我必须发送语音数据包,然后等待 20 毫秒才能获得正常语音。我使用 system.threading.thread.sleep(20)。但是,我注意到声音很慢。但是当我 运行 另一个不同的应用程序时,声音变得正常。
经过一些调试,我发现 system.Threading.Thread.Sleep(20) 需要 31 毫秒,但如果我 运行 另一个不同的应用程序,Thread.Sleep (20) 将始终准确。
为了使线程准确休眠 20 毫秒并且同时不影响 PC 性能,我可以使用哪些其他替代方法。
谢谢,
Sleep(20)
表示睡眠至少20毫秒。基本上,它会挂起线程并且不会在指定的延迟内恢复调度。在那之后,线程仍然需要被调度才能真正恢复 运行。取决于其他线程 运行 可能立即或稍后。这里没有保证。
documentation 调用此:
The system clock ticks at a specific rate called the clock resolution. The actual timeout might not be exactly the specified timeout, because the specified timeout will be adjusted to coincide with clock ticks. For more information on clock resolution and the waiting time, see the Sleep function topic. This method calls the Sleep function from the Windows system APIs.
如前所述,准确的计时通常需要一个不会被时间分割的thread/process,为此,您必须Spin
而不是Sleep
。
选项 1
如果你想要绝对的准确性而不是其他任何东西,我会使用带有秒表的专用高优先级线程。
bool running = true;
Thread t = new Thread(() =>
{
Stopwatch sw = Stopwatch.StartNew();
while (running)
{
if (sw.ElapsedMilliseconds >= 20)
{
RunCode();
sw.Restart();
}
}
}) { Priority = ThreadPriority.Highest, IsBackground = true };
t.Start();
// ...
running = false;
t.Join();
选项 2
瘦了一点,运行 不是在不同的线程上,但仍然旋转。
while (true)
{
SpinWait.SpinUntil(() => false, TimeSpan.FromMilliseconds(20));
RunCode();
}
选项 3
一些开源高分辨率定时器代码。例如https://gist.github.com/HakanL/4669495