在 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中文網其他相關文章!