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 對象,主線程於是跳出迴圈,終止程式。