首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于C# timer的时间精密度

2012-08-30 
关于C# timer的时间精度现在在学C#的winform编程,但是发现timer的时间精度不是横高,有五十多ms,需要提高精

关于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;      }    }  }} 

热点排行