C# - 计时器Timer
System.Timers.Timer
服务器计时器,允许指定在应用程序中引发事件的重复时间间隔。
using System.Timers;
// 在应用程序中生成定期事件
public class Timer : Component, ISupportInitialize {
public double Interval { get; set; }
public bool Enabled { get; set; } // 开始/停止引发事件Elapsed
public Timer();
public Timer(double interval);
public void Start(); // 启动Timer
public void Stop(); // 停止Timer
public void Close(); // 关闭Timer并释放其占用的资源
// 释放当前Timer使用的所有资源
// true:释放托管资源和非托管资源;false:仅释放非托管资源
protected override void Dispose(bool disposing);
public event ElapsedEventHandler Elapsed;
}
其中, public delegate void ElapsedEventHandler(object sender, ElapsedEventArgs e);
使用示例:
// 定时触发OnEventClick函数 System.Timers.Timer MyTimer = new System.Timers.Timer(); MyTimer.Elapsed += OnEventClick; MyTimer.Interval = 3 * 1000; MyTimer.Enabled = true;
System.Threading.Timer
线程计时器,允许在线程池线程上执行回调方法。
using System.Timers;
// 提供以指定的时间间隔执行方法的机制
public sealed class Timer : MarshalByRefObject, IDisposable {
public Timer(TimerCallback callback);
public Timer(TimerCallback callback, object state, xxx);
public bool Change(int dueTime, int period);
public void Dispose(); // 释放当前Timer实例使用的所有资源
public bool Dispose(WaitHandle notifyObject); // 同时释放信号
}
其中, public delegate void TimerCallback(object state);
---
纵使山重水复,亦会柳暗花明
sunqh1991@163.com
欢迎关注,互相交流

浙公网安备 33010602011771号