System.Threading.Timer 專為週期性喚醒執行場景設計。啟動後,系統自動建立背景線程,按指定間隔調用回調方法,無需手動管理線程生命週期。
Timer timer = new Timer(
TimerCallback callback, // 要執行的回調方法
object state, // 傳遞給回調的狀態對象
int dueTime, // 首次延遲時間(毫秒),0 表立即啟動
int period // 後續間隔時間(毫秒),Timeout.Infinite 禁用週期
);
運行中可隨時修改定時器參數:
// 1 秒後首次執行,之後每 2 秒執行一次
timer.Change(1000, 2000);
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();
TimerCallback timerDelegate = new TimerCallback(CheckStatus);
// 1秒後開始,每1秒執行一次
Timer timer = new Timer(timerDelegate, s, 1000, 1000);
s.tmr = timer;
// 主線程等待定時器結束
while (s.tmr != null)
Thread.Sleep(0);
Console.WriteLine("Timer example done.");
Console.ReadLine();
}
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)
{
// 第5次:改為10秒後首次,之後每2秒
s.tmr.Change(10000, 2000);
Console.WriteLine("changed");
}
if (s.counter == 10)
{
Console.WriteLine("disposing of timer");
s.tmr.Dispose();
s.tmr = null; // 觸發主線程退出循環
}
}
}
}
Change(10000, 2000) 重設為10秒後重新開始,間隔2秒Dispose() 釋放資源並置空引用while 循環檢測到 tmr == null 退出Dispose() 後不可再次使用,需重新實例化System.Timers.Timer 或多媒體定時器