任务延迟与线程睡眠分辨率精度 [英] Task Delay vs Thread Sleep Resolution Accuracy
问题描述
我需要在特定时间后执行功能,因此我使用此代码.
i need to execute a function after a specific amount of time, therefore i use this code.
_start = DateTime.Now;
await Task.Delay(_app.Settings.AudioFileStartVarianz.BaseSpan).ContinueWith(x =>
{
Console.WriteLine(DateTime.Now - _start);
});
让我们说我要等待0.04秒.我现在的问题是,它的工作不够精确.调用该函数5次后,得到以下输出:
Lets say i want to wait for exactly 0.04 seconds. My problem now is that it's not working precise enough. I get following output after calling the function 5 times:
- 00:00:00.0414220
- 00:00:00.0536098
- 00:00:00.0507841
- 00:00:00.0467757
- 00:00:00.0425790
如果我使用此代码,它将更好地工作
if i use this code it works way better
_start = DateTime.Now;
Thread.Sleep(_app.Settings.AudioFileStartVarianz.BaseSpan);
Console.WriteLine(DateTime.Now - _start);
- 00:00:00.0405879
- 00:00:00.0404284
- 00:00:00.0402117
- 00:00:00.0404908
- 00:00:00.0409088
但是现在我有一个问题,该功能没有异步运行,这很不好,因为我正在播放音频文件(NAudio).
But now i have the problem, that the function is not running asynchronous, what is bad because i am playing an audio file (NAudio).
有什么想法可以在这里等待异步,这样我的音频文件就不会停止吗?
Any ideas how i can here wait async, so that my audio file is not stopping?
KR曼努埃尔
推荐答案
两个调用 Thread.Sleep
&之间的区别 Task.Delay
是指 Thread.Sleep
调用OS方法来休眠线程,而 Task.Delay
创建一个 Timer
以模拟延迟.
The difference between the two calls, Thread.Sleep
& Task.Delay
, is that Thread.Sleep
calls an OS method to sleep the thread and Task.Delay
creates a Timer
to simulate the delay.
通话有效...
private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext);
...和...
promise.Timer = new Timer(state => ((DelayPromise)state).Complete(), promise, millisecondsDelay, Timeout.Infinite);
...分别.
现在Windows中的计时器分辨率非常低-大约有15ms的错误.我认为正是因为如此,您才能获得结果.
Now timers in windows are notoriously low resolution - with a 15ms error or so. I think it's because of this that you're getting your results.
坏消息是,如您所述,休眠线程不是异步的,因此要获得异步,您需要接受计时器解析错误.我认为您没有任何明智的方法可以避免这种情况.
The bad news is that sleeping the thread is not asynchronous, as you stated, so to get asynchrony you need to accept the timer resolution error. I don't think that there is any sane way for you to avoid it.
这篇关于任务延迟与线程睡眠分辨率精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!