static void Main(string[] args) { #region 定時器 TimerDemo td = new TimerDemo("TimerDemo", 1000); td.Enabled = true; td.TickEvent += TestHandler; Thread timer = new Thread(td.Run); timer.Start(); #endregion Console.ReadLine(); } /// <summary> /// 測試用事件 /// </summary> static void TestHandler() { Console.WriteLine(DateTime.Now.ToLongTimeString()); }
public class TimerDemo { //線程名 string _ThreadName; public string ThreadName { get { return _ThreadName; } private set { _ThreadName = value; } } //時間間隔 int _TimeInterval; public int TimeInterval { get { return _TimeInterval; } set { _TimeInterval = value; } } //當前計時器是否啟用 true:啟用 false:不啟用 bool _Enabled; public bool Enabled { get { return _Enabled; } set { _Enabled = value; } } //每隔一段時間需要啟動並執行事件 public delegate void TickEventHandler(); public event TickEventHandler TickEvent; /// <summary> /// 建立一個計時器(建構函式) /// </summary> /// <param name="ThreadName">線程名</param> /// <param name="TimeInterval">時間間隔</param> public TimerDemo(string ThreadName, int TimeInterval = int.MaxValue) { this.ThreadName = ThreadName; this.TimeInterval = TimeInterval; this.Enabled = false; } /// <summary> /// 定期執行事件 /// </summary> public void Run() { while (true) { //如果當前計時器並未啟用,則每隔一段時間檢測是否被啟用 if (!this.Enabled) { Thread.Sleep(100); continue; } //觸發事件TickEvent if (TickEvent != null) { TickEvent(); } //休眠一定的時間,等待下一個迴圈 Thread.Sleep(TimeInterval % 100); for (int temp = 0; temp < TimeInterval / 100; temp++) { Thread.Sleep(100); if (!this.Enabled) { break; } } } } }