c# 定时触发事件的正确姿势

655Z技术栈 C#编程 2025年07月12日 5

在C#中,可以使用System.Timers.Timer类来实现定时触发事件。以下是正确的姿势:

  1. 创建一个Timer对象,并设置Interval属性为触发时间间隔(单位为毫秒)。
  2. 指定一个事件处理方法,用于处理Timer.Elapsed事件(即定时触发的事件)。
  3. 启动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方法释放资源。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”