Home > Backend Development > C++ > How Can I Create a Precise and Reliable Timer in C#?

How Can I Create a Precise and Reliable Timer in C#?

Linda Hamilton
Release: 2025-01-18 17:52:13
Original
114 people have browsed it

How Can I Create a Precise and Reliable Timer in C#?

Building a High-Precision, Reliable Timer in C#

For creating a highly accurate and dependable timer in C#, the System.Timers.Timer class provides a robust solution. This class allows you to schedule tasks at specific intervals.

The Interval property of the Timer object sets the time between timer events. Setting this to 15000 milliseconds (15 seconds) triggers the associated method every 15 seconds.

Below is a code example showcasing the Timer class:

<code class="language-csharp">using System;
using System.Timers;

public class TimerExample
{
    public static void Main(string[] args)
    {
        // Create a timer with a 15-second interval
        Timer timer = new Timer(15000); 
        timer.Elapsed += OnTimedEvent; // Attach the event handler
        timer.Start(); // Start the timer

        Console.WriteLine("Press 'q' to exit.");
        while (Console.ReadKey().Key != ConsoleKey.Q) { } // Keep the console app running
    }

    // Method executed when the timer elapses
    private static void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Timer event triggered.");
    }
}</code>
Copy after login

This code creates a timer that calls the OnTimedEvent method every 15 seconds. The Console.ReadKey() method keeps the console application running until the user presses 'q'.

The above is the detailed content of How Can I Create a Precise and Reliable Timer 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template