Home > Backend Development > C++ > How to Add a Timer to a C# Console Application?

How to Add a Timer to a C# Console Application?

Linda Hamilton
Release: 2025-01-20 04:56:16
Original
703 people have browsed it

How to Add a Timer to a C# Console Application?

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>
Copy after login

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!

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