High-Resolution Timer in C#
System.Timer class is a commonly used timer in C# that raises an event on expiration. However, for high-resolution timing, it falls short. This article explores solutions for creating a high-resolution timer that fires an event at 1 ms intervals.
NET Framework Limitations
The .NET framework does not offer built-in support for high-resolution timers. However, the Multimedia Timer API in Windows provides a mechanism for high-resolution timer events.
Multimedia Timer
The Multimedia Timer API provides a timer that can be configured with a resolution of up to 1 ms. The following code demonstrates its usage:
class MultimediaTimer : IDisposable { // ... public int Interval { get { return interval; } set { // ... } } public int Resolution { get { return resolution; } set { // ... } } public void Start() { // ... } public void Stop() { // ... } public event EventHandler Elapsed; }
Code Example
Here's a complete example that utilizes the Multimedia Timer:
class Program { public static void Main(string[] args) { TestThreadingTimer(); TestMultimediaTimer(); } private static void TestMultimediaTimer() { Stopwatch s = new Stopwatch(); using (var timer = new MultimediaTimer() { Interval = 1 }) { timer.Elapsed += (o, e) => Console.WriteLine(s.ElapsedMilliseconds); s.Start(); timer.Start(); Console.ReadKey(); timer.Stop(); } } // ... }
Note: The Multimedia Timer API can impact system performance, so it's important to use it judiciously. It's also worth considering that the system may experience fluctuations in performance, leading to variations in the timer's reliability.
The above is the detailed content of How Can I Create a High-Resolution Timer in C# with 1ms Accuracy?. For more information, please follow other related articles on the PHP Chinese website!