C#  中的計時器


用於設定計時器的名稱空間是 System.Timers。Timer 類在設定的時間間隔後生成一個事件,並可以選擇生成重複事件。

首先,為 5 秒間隔建立一個計時器物件 −

timer = new System.Timers.Timer(5000);

為計時器設定事件經過時間。當時間間隔過去時,則會發生這件事 −

timer.Elapsed += OnTimedEvent;

現在啟動計時器。

timer.Enabled = true;

示例

using System;
using System.Timers;

public class Demo {
   private static Timer timer;

   public static void Main() {
      timer = new System.Timers.Timer();
      timer.Interval = 5000;

      timer.Elapsed += OnTimedEvent;
      timer.AutoReset = true;
      timer.Enabled = true;

      Console.WriteLine("Press the Enter key to exit anytime... ");
      Console.ReadLine();
   }

   private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) {
      Console.WriteLine("Raised: {0}", e.SignalTime);
   }
}

更新於: 21-6 月-2020

2 千+ 次瀏覽

開啟你的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.