欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#多線程學(xué)習(xí)之(五)使用定時(shí)器進(jìn)行多線程的自動(dòng)管理

 更新時(shí)間:2015年04月07日 10:10:27   作者:樂樂010  
這篇文章主要介紹了C#多線程學(xué)習(xí)之使用定時(shí)器進(jìn)行多線程的自動(dòng)管理,實(shí)例分析了C#使用timer定時(shí)器類實(shí)現(xiàn)針對(duì)多線程的自動(dòng)管理功能,非常具有實(shí)用價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了C#多線程學(xué)習(xí)之使用定時(shí)器進(jìn)行多線程的自動(dòng)管理。分享給大家供大家參考。具體分析如下:

Timer類:設(shè)置一個(gè)定時(shí)器,定時(shí)執(zhí)行用戶指定的函數(shù)。

定時(shí)器啟動(dòng)后,系統(tǒng)將自動(dòng)建立一個(gè)新的線程,執(zhí)行用戶指定的函數(shù)。

初始化一個(gè)Timer對(duì)象:

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類的程序示例(來源: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)建代理對(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;
  //主線程停下來等待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)用一次CheckStatus()方法,當(dāng)調(diào)用5次以后,在CheckStatus()方 法中修改了時(shí)間間隔為2秒,并且指定在10秒后重新開始。當(dāng)計(jì)數(shù)達(dá)到10次,調(diào)用Timer.Dispose()方法刪除了timer對(duì)象,主線程于是跳 出循環(huán),終止程序。

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論