日期:2014-05-18  浏览次数:21219 次

关于C# timer的时间精度
现在在学C#的winform编程,但是发现timer的时间精度不是横高,有五十多ms,需要提高精度到1ms,要怎么做??网上找了一下,说用API,具体指??还有说用winform编达不到这么高的精度,是不是真的??

------解决方案--------------------
参考一下:
http://topic.csdn.net/u/20120514/16/0235fd54-b240-4035-90a5-04960c52524a.html
------解决方案--------------------
如果你的要求是精确到1ms之内,无论是控件Timer还是Thread Timer都无法达到你的要求,正确的方法是调用API

C# code
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Win32
{
  internal class HiPerfTimer
  {
    [DllImport("Kernel32.dll")]
    private static extern bool QueryPerformanceCounter(
      out long lpPerformanceCount);

    [DllImport("Kernel32.dll")]
    private static extern bool QueryPerformanceFrequency(
      out long lpFrequency);

    private long startTime, stopTime;
    private long freq;

    // Constructor

    public HiPerfTimer()
    {
      startTime = 0;
      stopTime = 0;

      if (QueryPerformanceFrequency(out freq) == false)
      {
        // high-performance counter not supported

        throw new Win32Exception();
      }
    }

    // Start the timer

    public void Start()
    {
      // lets do the waiting threads there work

      Thread.Sleep(0);

      QueryPerformanceCounter(out startTime);
    }

    // Stop the timer

    public void Stop()
    {
      QueryPerformanceCounter(out stopTime);
    }

    // Returns the duration of the timer (in seconds)

    public double Duration
    {
      get
      {
        return (double)(stopTime - startTime) / (double) freq;
      }
    }
  }
}