Task.Delay的准确性 [英] Accuracy of Task.Delay

查看:55
本文介绍了Task.Delay的准确性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 C#/Xaml 中开发 Windows 10 通用应用程序,我正在使用 await Task.Delay(delayInMilliseconds) 暂停给定时间的方法.我的场景有点实时,所以它对时间变化非常敏感,我需要确保当我暂停一个方法时,比如 8 毫秒,它被暂停 8 毫秒.我注意到 ** Task.Delay ** 挂起方法的实际时间跨度与作为延迟参数传递的时间跨度不同,1 到 30 毫秒,每次调用中偏差"的长度不同.所以,当我想休眠 8 毫秒时,我的系统休眠了 9 到 39 毫秒,这完全破坏了我的场景.所以,我的问题是替代 ** Task.Delay ** 并达到良好精度的最佳方法是什么?暂时我用这个方法:

I'm developing Windows 10 Universal App in C#/Xaml, I'm using await Task.Delay(delayInMilliseconds) to suspend a method for given time. My scenario is somewhat realtime, so it's very sensitive to time changes, and I need to make sure that when i suspend a method for let's say 8 millisecods it is suspended for 8 millisecods. I have noticed that the actual time span for which ** Task.Delay ** suspends the method differes from what is passed as delay parameter, for 1 up to 30 ms, the length of "deviation" being different in each call. So, when I want to sleep for 8 milliseconds, my system sleeps for 9 to 39 milliseconds, and this completly ruins my scenario. So, my question what is the best way to substitute ** Task.Delay ** and to achieve good precision? For the time being I use this method:

 public static void Delay1(int delay)
    {
        long mt = delay * TimeSpan.TicksPerMillisecond;
        Stopwatch s = Stopwatch.StarNew();
        while (true)
        {
            if (s.Elapsed.TotalMilliseconds > delay)
            {
                return;
            }
        }
    }

但它猜测它消耗了大量资源,即处理器核心的 100%.如果用户的处理器内核数量很少,这将是非常不够的.

but it guees it consumes a lot of resources, that is 100% of a processor's core. If an user has small number of processor's cores, this would be very insufficient.

推荐答案

根据 msdn 由于系统时钟分辨率,不可能达到更高的精度:

According to msdn it's not possible to achieve more accuracy due to system clock resolution:

此方法取决于系统时钟.这意味着时间延迟将大约等于系统时钟的分辨率,如果毫秒延迟参数小于分辨率系统时钟,在 Windows 上约为 15 毫秒系统.

This method depends on the system clock. This means that the time delay will approximately equal the resolution of the system clock if the millisecondsDelay argument is less than the resolution of the system clock, which is approximately 15 milliseconds on Windows systems.

这篇关于Task.Delay的准确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆