C#多線程學習(五) 多線程的自動管理(定時器)

來源:互聯網
上載者:User

Timer類:設定一個定時器,定時執行使用者指定的函數。

定時器啟動後,系統將自動建立一個新的線程,執行使用者指定的函數。

初始化一個Timer對象:

Timer timer = new Timer(timerDelegate, s,1000, 1000);

// 第一個參數:指定了TimerCallback 委託,表示要執行的方法;

// 第二個參數:一個包含回調方法要使用的資訊的對象,或者為空白引用;

// 第三個參數:延遲時間——計時開始的時刻距現在的時間,單位是毫秒,指定為“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();

   //建立代理對象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;
}
   }
}
}

 

程式首先建立了一個定時器,它將在建立1秒之後開始每隔1秒調用一次CheckStatus()方法,當調用5次以後,在 CheckStatus()方法中修改了時間間隔為2秒,並且指定在10秒後重新開始。當計數達到10次,調用Timer.Dispose()方法刪除了 timer對象,主線程於是跳出迴圈,終止程式。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.