什么线程睡眠方法是最precise:Monitor.Wait VS System.Timer VS DispatchTimer VS Threading.Timer [英] What Thread sleep method is most precise: Monitor.Wait vs System.Timer vs DispatchTimer vs Threading.Timer

查看:116
本文介绍了什么线程睡眠方法是最precise:Monitor.Wait VS System.Timer VS DispatchTimer VS Threading.Timer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么.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 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.

这篇关于什么线程睡眠方法是最precise:Monitor.Wait VS System.Timer VS DispatchTimer VS Threading.Timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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