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>
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!