在C#中,可以使用System.Timers.Timer类来实现定时触发事件。以下是正确的姿势:
- 创建一个Timer对象,并设置Interval属性为触发时间间隔(单位为毫秒)。
- 指定一个事件处理方法,用于处理Timer.Elapsed事件(即定时触发的事件)。
- 启动Timer对象。
下面是一个示例代码:
using System;
using System.Timers;
class Program
{
static void Main()
{
Timer timer = new Timer();
timer.Interval = 1000; // 设置触发时间间隔为1秒
timer.Elapsed += OnTimedEvent; // 指定事件处理方法
timer.AutoReset = true; // 设置为true表示定时触发事件将一直重复
timer.Enabled = true; // 启动Timer
Console.WriteLine("Press Enter to stop the timer...");
Console.ReadLine();
timer.Stop();
timer.Dispose();
}
static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Timer triggered at: {0}", e.SignalTime);
}
}
在上面的示例中,Timer对象每隔1秒触发一次OnTimedEvent方法,并输出当前时间。可以根据需求调整Interval属性来设置不同的触发时间间隔。当不再需要触发事件时,记得调用Stop方法停止Timer对象,并调用Dispose方法释放资源。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1099602.html