如果你的要求是精确到1ms之内,无论是控件Timer还是Thread Timer都无法达到你的要求,正确的方法是调用APIusing 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; } } } }
所以精准度不可靠,上一次没有执行完,则下一次就不会引发。高性能计时器使用System.Timer或线程计时器
System.Threading.Thread
或
System.Threading.Timer
http://topic.csdn.net/u/20120514/16/0235fd54-b240-4035-90a5-04960c52524a.html
System.Threading.Timer, System.Timers.Timer
精度也只能达到20ms120.0069
107.0061
113.0065
106.0061
109.0062
111.0063
106.0061
112.0064
108.0062
113.0065
107.0061
106.006
118.0068
101.0058
109.0062
115.0066
106.006
106.0061
114.0065
107.0061
106.0061
113.0065
106.006
114.0066
107.0061
106.006
115.0066
106.0061
107.0061
114.0065
106.0061
112.0064
109.0062
107.0061
108.0062
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;
}
}
}
}
private static extern Int32 设置系统时钟精度(Int32 _毫秒精度_);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod")]
private static extern Int32 恢复系统时钟精度(Int32 _毫秒精度_); 设置系统时钟精度(1);不用后可以 恢复系统时钟精度(1);