Timer 類:
設置一個定時器,定時執行用戶指定的函數。定時器啟動后,系統將自動建立一個新的線程,執行用戶指定的函數。
using System;
using System.Threading;
namespace ThreadExample
{
class TimerExampleState
{
public int counter = 0;
public Timer tmr;
}
class App
{
public static void Main()
{
TimerExampleState s = new TimerExampleState();
// 創建代理對象 System.Threading.TimerCallback,該代理將被定時調用
TimerCallback timerDelegate = new TimerCallback(CheckStatus);
// 創建一個時間間隔為 1s 的定時器
// 第1個參數:指定了 TimerCallback 委托,表示要執行的方法;
// 第2個參數:一個包含回調方法要使用的信息的對象,或者為空引用;
// 第3個參數:延遲時間--計時開始的時刻距現在的時間,單位是毫秒,指定為"0"表示 立即啟動計時器;
// 第4個參數:定時器的時間間隔--計時開始后,每隔這么長的一段時間,TimerCallback 所代表的方法將被調用一次
Timer timer = new Timer(timerDelegate, s, 1000, 1000);
s.tmr = timer;
// 主線程停下來等待 Timer 對象的終止
while (s.tmr != null)
{
Thread.Sleep(0);
}
Console.WriteLine("Timer example done.");
Console.ReadLine();
}
/// <summary>
/// 下面是被定時調用的方法
/// </summary>
/// <param name="state"></param>
static void CheckStatus(Object state)
{
TimerExampleState s = (TimerExampleState)state;
s.counter++;
Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, s.counter);
if (s.counter == 5)
{
//使用 Change 方法改變了時間間隔為2秒,再等待10秒
(s.tmr).Change(10000, 2000);
Console.WriteLine("changed");
}
if (s.counter == 10)
{
Console.WriteLine("disposing of timer!");
s.tmr.Dispose();
s.tmr = null;
}
}
}
}
程序首先創建了一個定時器,它將在創建 1 秒之后開始每隔 1 秒調用一次 CheckStatus() 方法。當調用 5 次以后,CheckStatus() 方法中修改了時間間隔為 2 秒,在並且指定在 10 秒后重新開始。當計數達到 10 次, 調用 Timer.Dispose()方法刪除了 timer 對象,主線程於是跳出循環,終止程序。