CSharp中的Timer,使用样例解释下
时间: 2023-06-02 07:06:09 浏览: 70
Timer 是 C# 中一个非常常用的定时器类。使用 Timer 可以实现定时执行某个方法或者操作。下面是一个 Timer 的使用样例:
```
using System;
using System.Timers;
public class TimerExample
{
private static Timer _timer;
public static void Main()
{
_timer = new Timer(1000); // 创建一个 1 秒钟的 Timer
_timer.Elapsed += OnTimedEvent; // 绑定 Timer 的 Elapsed 事件
_timer.AutoReset = true; // 设置 Timer 持续执行
_timer.Enabled = true; // 开始 Timer
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine(); // 暂停程序,按下 Enter 键结束
_timer.Stop(); // 停止 Timer
_timer.Dispose(); // 清理 Timer 资源
Console.WriteLine("Terminating the application...");
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
}
}
```
在这个样例中,首先创建了一个 1 秒钟的 Timer 对象。然后设置 Timer 的 Elapsed 事件,绑定了一个 OnTimedEvent 方法,该方法会在 Timer 经过 1 秒后被触发。最后启动 Timer,程序会每隔 1 秒输出一行文字。用户可以按下 Enter 键结束程序,这时候会停止 Timer 并且释放 Timer 资源。