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