Integrating Timers into Your C# Console Application
This guide demonstrates how to implement timer functionality within your C# console application, enhancing its capabilities.
Leveraging the Timer Class
The Timer
class provides a straightforward method for creating timers in C#. It allows you to define a callback function that executes repeatedly at specified intervals. Consider this example:
<code class="language-csharp">using System; using System.Threading; public class ConsoleTimer { private Timer timerInstance; private int count; public void InitiateTimer() { // Initiate a timer, triggering the TimerCallback method every 2 seconds (2000 milliseconds) timerInstance = new Timer(TimerCallback, null, 0, 2000); } private void TimerCallback(object state) { Console.WriteLine($"Timer event: {++count}"); } public static void Main(string[] args) { var consoleTimer = new ConsoleTimer(); consoleTimer.InitiateTimer(); Console.WriteLine("Press Enter to halt the timer."); Console.ReadLine(); // Properly stop the timer timerInstance.Dispose(); } }</code>
This code creates a timer using InitiateTimer
that calls TimerCallback
every 2 seconds. TimerCallback
increments a counter and displays the count to the console. The Main
method starts the timer, waits for user input, and then stops the timer using Dispose()
.
The above is the detailed content of How to Add a Timer to a C# Console Application?. For more information, please follow other related articles on the PHP Chinese website!