C# 執行緒:定時器的使用
阿新 • • 發佈:2019-01-08
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { class TimerExampleState { public int counter = 0; public Timer tmr; } class Program { static void Main(string[] args) { TimerExampleState s = new TimerExampleState();
//建立代理物件TimerCallback,該代理將被定時呼叫 TimerCallback timerDelegate = new TimerCallback(CheckStatus); //建立一個時間間隔為1s的定時器 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(); } //下面是被定時呼叫的方法 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方法改變了時間間隔 (s.tmr).Change(10000, 2000); Console.WriteLine("changed"); } if (s.counter == 10) { Console.WriteLine("disposing of timer"); s.tmr.Dispose(); s.tmr = null; } } } }