C# CheckStatus()方法
C#語(yǔ)言還是比較常見的東西,這里我們主要介紹C# CheckStatus()方法,包括介紹設(shè)置一個(gè)定時(shí)器,定時(shí)執(zhí)行用戶指定的函數(shù)等方面。
Timer類:設(shè)置一個(gè)定時(shí)器,定時(shí)執(zhí)行用戶指定的函數(shù)。
定時(shí)器啟動(dòng)后,系統(tǒng)將自動(dòng)建立一個(gè)新的線程,執(zhí)行用戶指定的函數(shù)。
- Timer timer = new Timer(timerDelegate, s,1000, 1000);
- // ***個(gè)參數(shù):指定了TimerCallback 委托,表示要執(zhí)行的方法;
- // 第二個(gè)參數(shù):一個(gè)包含回調(diào)方法要使用的信息的對(duì)象,或者為空引用;
- // 第三個(gè)參數(shù):延遲時(shí)間——計(jì)時(shí)開始的時(shí)刻距現(xiàn)在的時(shí)間,單位是毫秒,
指定為“0”表示立即啟動(dòng)計(jì)時(shí)器;- // 第四個(gè)參數(shù):定時(shí)器的時(shí)間間隔——計(jì)時(shí)開始以后,每隔這么長(zhǎng)的一段時(shí)間,
TimerCallback所代表的方法將被調(diào)用一次,單位也是毫秒。
指定 Timeout.Infinite 可以禁用定期終止。
Timer.Change()方法:修改定時(shí)器的設(shè)置。(這是一個(gè)參數(shù)類型重載的方法)使用示例:timer.Change(1000,2000);
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();
- //創(chuàng)建代理對(duì)象TimerCallback,該代理將被定時(shí)調(diào)用
- TimerCallback timerDelegate = new TimerCallback(CheckStatus);
- //創(chuàng)建一個(gè)時(shí)間間隔為1s的定時(shí)器
- Timer timer = new Timer(timerDelegate, s,1000, 1000);
- s.tmr = timer;
- //主線程停下來(lái)等待Timer對(duì)象的終止
- while(s.tmr != null)
- Thread.Sleep(0);
- Console.WriteLine("Timer example done.");
- Console.ReadLine();
- }
- //下面是被定時(shí)調(diào)用的方法
- 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方法改變了時(shí)間間隔
- (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)建了一個(gè)定時(shí)器,它將在創(chuàng)建1秒之后開始每隔1秒調(diào)用一次C# CheckStatus()方法,當(dāng)調(diào)用5次以后,在C# CheckStatus()方法中修改了時(shí)間間隔為2秒,并且指定在10秒后重新開始。當(dāng)計(jì)數(shù)達(dá)到10次,調(diào)用Timer.Dispose()方法刪除了timer對(duì)象,主線程于是跳出循環(huán),終止程序。
【編輯推薦】