C#多線程學習之(五)使用定時器進行多線程的自動管理
本文實例講述了C#多線程學習之使用定時器進行多線程的自動管理。分享給大家供大家參考。具體分析如下:
Timer類:設置一個定時器,定時執(zhí)行用戶指定的函數。
定時器啟動后,系統(tǒng)將自動建立一個新的線程,執(zhí)行用戶指定的函數。
初始化一個Timer對象:
Timer timer = new Timer(timerDelegate, s,1000, 1000);
第一個參數:指定了TimerCallback 委托,表示要執(zhí)行的方法;
第二個參數:一個包含回調方法要使用的信息的對象,或者為空引用;
第三個參數:延遲時間——計時開始的時刻距現在的時間,單位是毫秒,指定為“0”表示立即啟動計時器;
第四個參數:定時器的時間間隔——計時開始以后,每隔這么長的一段時間,TimerCallback所代表的方法將被調用一次,單位也是毫秒。指定 Timeout.Infinite 可以禁用定期終止。
Timer.Change()方法:修改定時器的設置。(這是一個參數類型重載的方法)
使用示例:
timer.Change(1000,2000);
Timer類的程序示例(來源:MSDN):
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(); //創(chuàng)建代理對象TimerCallback,該代理將被定時調用 TimerCallback timerDelegate = new TimerCallback(CheckStatus); //創(chuàng)建一個時間間隔為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; } } } }
程序首先創(chuàng)建了一個定時器,它將在創(chuàng)建1秒之后開始每隔1秒調用一次CheckStatus()方法,當調用5次以后,在CheckStatus()方 法中修改了時間間隔為2秒,并且指定在10秒后重新開始。當計數達到10次,調用Timer.Dispose()方法刪除了timer對象,主線程于是跳 出循環(huán),終止程序。
希望本文所述對大家的C#程序設計有所幫助。
相關文章
C#執(zhí)行存儲過程并將結果填充到GridView的方法
這篇文章主要介紹了C#執(zhí)行存儲過程并將結果填充到GridView的方法,結合實例形式分析了C#存儲過程操作及GridView控件相關操作技巧,需要的朋友可以參考下2017-02-02