using System;
using System.Timers;
class Program
{
static void Main()
{
// 创建一个定时器,设置间隔时间为1秒(1000毫秒)
Timer timer = new Timer(1000);
// 定义定时器触发时的事件处理程序
timer.Elapsed += OnTimedEvent;
// 启动定时器
timer.Start();
// 输出启动信息
Console.WriteLine("按任意键停止计时器...");
Console.ReadLine();
// 停止定时器
timer.Stop();
timer.Dispose();
}
// 定时器触发时调用的方法
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("定时器触发时间: " + e.SignalTime);
}
}
System.Timers.Timer
类创建一个定时器对象,并设置其间隔时间为1000毫秒(即1秒)。Elapsed
事件定义一个处理方法 OnTimedEvent
,该方法会在每次定时器触发时被调用。timer.Start()
启动定时器,使用 timer.Stop()
和 timer.Dispose()
停止并释放定时器资源。希望这个示例能帮助你理解如何在C#中使用定时器。
下一篇:c# 数组转list
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站