在 C# 中,System.Timer 类可用于创建一个以指定时间间隔引发事件的计时器。但是,System.Timer 类的分辨率有限,可能不适合需要高分辨率计时的应用程序。
要创建以特定时间间隔引发事件的高分辨率计时器,您可以使用多媒体定时器 API。多媒体计时器 API 是一个 Windows API,提供高分辨率计时器,可用于以小至 1 毫秒的间隔引发事件。
要使用多媒体计时器 API 创建高分辨率计时器,您需要可以使用以下代码:
using System.Runtime.InteropServices; public class HighResolutionTimer { private bool disposed = false; private int interval, resolution; private UInt32 timerId; // Hold the timer callback to prevent garbage collection. private readonly MultimediaTimerCallback Callback; public HighResolutionTimer() { Callback = new MultimediaTimerCallback(TimerCallbackMethod); Resolution = 5; Interval = 10; } ~HighResolutionTimer() { Dispose(false); } public int Interval { get { return interval; } set { CheckDisposed(); if (value < 0) throw new ArgumentOutOfRangeException("value"); interval = value; if (Resolution > Interval) Resolution = value; } } // Note minimum resolution is 0, meaning highest possible resolution. public int Resolution { get { return resolution; } set { CheckDisposed(); if (value < 0) throw new ArgumentOutOfRangeException("value"); resolution = value; } } public bool IsRunning { get { return timerId != 0; } } public void Start() { CheckDisposed(); if (IsRunning) throw new InvalidOperationException("Timer is already running"); // Event type = 0, one off event // Event type = 1, periodic event UInt32 userCtx = 0; timerId = NativeMethods.TimeSetEvent((uint)Interval, (uint)Resolution, Callback, ref userCtx, 1); if (timerId == 0) { int error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } } public void Stop() { CheckDisposed(); if (!IsRunning) throw new InvalidOperationException("Timer has not been started"); StopInternal(); } private void StopInternal() { NativeMethods.TimeKillEvent(timerId); timerId = 0; } public event EventHandler Elapsed; public void Dispose() { Dispose(true); } private void TimerCallbackMethod(uint id, uint msg, ref uint userCtx, uint rsv1, uint rsv2) { var handler = Elapsed; if (handler != null) { handler(this, EventArgs.Empty); } } private void CheckDisposed() { if (disposed) throw new ObjectDisposedException("MultimediaTimer"); } private void Dispose(bool disposing) { if (disposed) return; disposed = true; if (IsRunning) { StopInternal(); }
以上是如何用 C# 创建高分辨率计时器?的详细内容。更多信息请关注PHP中文网其他相关文章!