.net thread.sleep 不准确
我快疯了!!我通过 gsm 和语音规范发送音频,我必须发送语音数据包,然后等待 20 毫秒才能获得正常语音.我使用 system.threading.thread.sleep(20).但是,我注意到声音很慢.但是当我运行另一个不同的应用程序时,声音变得正常.
I am getting crazy !!. I am sending audio over gsm and by voice specifications, I must send voice date packets then wait for 20 milliseconds to get normal voice. I use system.threading.thread.sleep(20). However, I noticed that sound is slow .But when i run another different application , sound gets normal.
经过一些调试,我发现 system.Threading.Thread.Sleep(20) 需要 31 毫秒,但如果我运行另一个不同的应用程序,Thread.Sleep (20) 将始终准确.
After some debugging, i found that system.Threading.Thread.Sleep(20) takes 31 milliseconds , but if I run another different application, the Thread.Sleep (20) will always be accurate.
为了使线程准确休眠 20 毫秒,我可以使用哪些其他替代方法?同时不影响PC性能.
what are the other alternatives that I can use in order to make the thread sleep for 20 Milli-seconds accurately & at the same time does not impact PC performance.
谢谢,
如前所述,准确的计时通常需要一个不会被时间切片的线程/进程,要做到这一点,你必须Spin
而不是 睡眠
.
As mentioned, accurate timings generally need a thread/process that is not going to time sliced out, to do this, you must Spin
rather than Sleep
.
选项 1
如果您想要绝对的准确性,我会使用带有秒表的专用高优先级线程.
If you want absolute accuracy over anything else, I would use a dedicated high priority thread with a Stopwatch.
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
稍微瘦一点,不会在不同的线程上运行但仍然旋转.
Bit more slimmed down, doesn't run on a different thread but still spins.
while (true)
{
SpinWait.SpinUntil(() => false, TimeSpan.FromMilliseconds(20));
RunCode();
}
选项 3
一些开源的高分辨率定时器代码.例如https://gist.github.com/HakanL/4669495
Some open source high resolution timer code. e.g. https://gist.github.com/HakanL/4669495