温馨提示×

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

c#
小樊
139
2024-07-14 05:43:25
栏目: 编程语言

在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方法释放资源。

0