Home > Backend Development > C++ > How Can I Implement Precise Timers in C#?

How Can I Implement Precise Timers in C#?

DDD
Release: 2025-01-18 17:56:09
Original
887 people have browsed it

How Can I Implement Precise Timers in C#?

Creating Accurate Timers in C#

Building reliable and precise timers in C# requires careful consideration. For example, a 15-second timer should ideally trigger within a narrow tolerance, perhaps between 14.5 and 15.5 seconds.

The System.Timers.Timer Class: A Robust Solution

The System.Timers.Timer class offers a superior approach to timer implementation. The following code demonstrates its use:

<code class="language-csharp">public static void Main()
{
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    timer.Interval = 5000; // 5 seconds
    timer.Enabled = true;

    Console.WriteLine("Press 'q' to quit.");
    while (Console.Read() != 'q') { }
}

// Timer event handler
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Console.WriteLine("Timer triggered!");
}</code>
Copy after login

Functionality Explained:

The System.Timers.Timer class fires the Elapsed event at intervals specified by the Interval property (in milliseconds). This example sets the interval to 5000 milliseconds (5 seconds). The OnTimedEvent method executes the desired code each time the event is raised.

This method leverages the operating system's timer mechanisms, making it significantly more precise and dependable than alternative methods like polling or thread sleeping.

The above is the detailed content of How Can I Implement Precise Timers in C#?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template