📜  c# timer - C# (1)

📅  最后修改于: 2023-12-03 14:59:40.944000             🧑  作者: Mango

C# Timer

C# Timer class provides functionality to execute a block of code or a method at specified intervals. It allows developers to schedule tasks or operations to be performed repeatedly or after a certain period of time.

Creating a Timer

To use the Timer class in C#, you need to include the System.Timers namespace. Here's an example of creating a timer:

using System;
using System.Timers;

public class Program
{
    private static Timer timer;

    public static void Main()
    {
        timer = new Timer(1000); // Timer with 1 second interval (1000 milliseconds)
        timer.Elapsed += TimerElapsed; // Set the event handler for the Elapsed event
        timer.AutoReset = true; // Set AutoReset property to true for continuous execution
        timer.Enabled = true; // Start the timer

        Console.WriteLine("Press any key to stop the timer.");
        Console.ReadKey();
        timer.Stop(); // Stop the timer
    }

    private static void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        // Code to be executed at each interval
        Console.WriteLine("Timer elapsed at: " + e.SignalTime);
    }
}

In this example, a Timer object is created with a 1-second interval (1000 milliseconds). The Elapsed event is subscribed to a method called TimerElapsed, which will be executed at each interval.

The AutoReset property is set to true to continuously execute the TimerElapsed method. Finally, the timer is started by setting the Enabled property to true.

Stopping the Timer

To stop the timer, you can call the Stop() method on the Timer object. In the example above, we stop the timer when any key is pressed in the console.

timer.Stop();
Multiple Timer Instances

You can create multiple timer instances to perform different tasks at different intervals. Each timer instance will require a separate event handler method.

Summary

The C# Timer class is a powerful tool for scheduling and executing tasks at specified intervals. It is widely used in applications that require periodic updates or background operations.

Remember to dispose of the Timer object properly when you no longer need it to free up system resources.

For more information, refer to the Timer Class documentation.

**Note: The Timer class used in this example is from System.Timers. There is also a Timer class in the System.Threading namespace, which provides similar functionality.