Home > Backend Development > C++ > How Can I Create a High-Resolution Timer in C# with 1ms Accuracy?

How Can I Create a High-Resolution Timer in C# with 1ms Accuracy?

Linda Hamilton
Release: 2025-01-17 10:57:13
Original
833 people have browsed it

How Can I Create a High-Resolution Timer in C# with 1ms Accuracy?

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;
}
Copy after login

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();
        }
    }

    // ...
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template