淺談C#中的多線程編程[3]

來源:互聯網
上載者:User

  之前複習了有關Thread類的相關知識,最後複習下有關定時器Timer的使用方法。
  Timer類的繼承層次為System.Object-System.MarshallByRefObject,其建構函式有下面的幾種重載方式:
  
  相對應的建構函式說明如下:
  
  Timer類是一個定時器,定時執行使用者指定的函數,當定時器啟動後,系統自動建立一個新的線程,執行指定的函數,我們可以通過下面的方式來初始化一個Timer對象:
  Timer timer = new Timer(timerDelfgate,obj,0,1000);
  第一個參數是TimerCallback委託,表示要執行的方法;
  第二個參數是一個包含回調方法要使用的資訊的對象,可以為空白引用;
  第三個參數是順延強制的時間,單位是毫秒,若為"0",表示立即開始。
  第四個參數是指定時器的時間間隔,每隔那麼長的一段時間,TimerCallBack所代表的方法將被調用一次,單位是毫秒。

  Timer類所持有的方法如下:
  
  相對應的說明如下:
  

  下面是Timer類的範例程式碼:       

View Code

using System;
using System.Threading;

class TimerExample
{
static void Main()
{
// Create an event to signal the timeout count threshold in the
// timer callback.
AutoResetEvent autoEvent = new AutoResetEvent(false);

StatusChecker statusChecker = new StatusChecker(10);

// Create an inferred delegate that invokes methods for the timer.
TimerCallback tcb = statusChecker.CheckStatus;

// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);

// When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n");

// When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}

class StatusChecker
{
private int invokeCount;
private int maxCount;

public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}

// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());

if(invokeCount == maxCount)
{
// Reset the counter and signal Main.
invokeCount = 0;
autoEvent.Set();
}
}
}

  最後為了把知識運用到實踐中,用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.