什么线程睡眠方法是最precise:Monitor.Wait VS System.Timer VS DispatchTimer VS Threading.Timer线程、睡眠、方法、Monitor

2023-09-05 04:42:53 作者:旧予

什么.NET对象(或技术)是最precise在启动一个线程,每个XXX毫秒?什么是权衡?

What .NET object (or technique) is the most precise at launching a thread every XXX milliseconds? What are the tradeoffs?

例如:

        int maxDurationMs = 1000;
        while (true)
        {
            DateTime dt = DateTime.UtcNow;
            DoQuickStuff()
            TimeSpan duration1 =  DateTime.UtcNow - dt;
            int sleepTime = maxDurationMs - duration1.Milliseconds;
            if (sleepTime > 0)
                System.Threading.Thread.Sleep(sleepTime);
        }

       // CPU Intensive, but fairly accurate
       int maxDurationMs = 1000;
        while (true)
        {
            DateTime dt = DateTime.UtcNow;
            DoQuickStuff()
            while (true)
            {
                if (dt.AddMilliseconds(maxDurationMs) >= DateTime.UtcNow)
                    break;
            }
        }

做同样的事情的替代方法,但有不同程度的精确度和权衡(CPU等)

Alternate methods of doing the same thing, but with varying degrees of accuracy and tradeoffs (CPU, etc)

System.Timer DispatchTimer System.Threading.Timer 的Thread.join .NET 4.0任务 的Thread.Sleep() Monitor.Wait(OBJ,时间跨度) 多媒体计时器(感谢布赖恩·基甸) Win32的高分辨率定时器 在其他什么东西? System.Timer DispatchTimer System.Threading.Timer Thread.Join .NET 4.0 Task Thread.Sleep() Monitor.Wait(obj, timespan) Multimedia Timers (thanks Brian Gideon) Win32 High Resolution timers Something else?

推荐答案

我从来没有真正使用过自己,但的多媒体计时器据说有Windows中的任何计时器服务的最佳分辨率。在.NET BCL没有一个包装这个计时器服务又那么你将不得不做的P / Invoke调用自己。

I have never actually used them myself, but Multimedia Timers are said to have the best resolution of any timer service in Windows. The .NET BCL does not have a wrapper for this timer service yet so you will have to do the P/Invoke calls yourself.

另一种选择可能是使用秒表加上一些标准 Thread.sleep代码在紧密循环中调用。我不知道你有多大的运气都使用这种方法,但它可能会比普通的老式 Thread.sleep代码通话本身更准确。我从来没有尝试过,但任何事情都是值得一试的,我想。

Another option might be to use Stopwatch together with some standard Thread.Sleep calls in a tight loop. I am not sure how much luck you would have with this approach, but it might be more accurate than a plain old Thread.Sleep call by itself. I have never tried it, but anything is worth a shot I suppose.

我做了一些实验,我发现,改变线程优先级,以 ThreadPriority.Highest 取得了相当大的差异。它由相当多的关于每个技术我试图减小的间隔的标准偏差。

I did some experiments and I discovered that changing the thread priority to ThreadPriority.Highest made a considerable difference. It reduced the standard deviation of the interval by quite a bit on each technique I tried.