C#中timer類的用法

來源:互聯網
上載者:User
C#中timer類的用法關於C#中timer類  在C#裡關於定時器類就有3個  
1.定義在System.Windows.Forms裡  
2.定義在System.Threading.Timer類裡  
3.定義在System.Timers.Timer類裡 

System.Windows.Forms.Timer是應用於WinForm中的,它是通過Windows訊息機制實現的,類似於VB或Delphi中的Timer控制項,內部使用API  SetTimer實現的。它的主要缺點是計時不精確,而且必須有訊息迴圈,Console  Application(控制台應用程式)無法使用。  
 
System.Timers.Timer和System.Threading.Timer非常類似,它們是通過.NET  Thread  Pool實現的,輕量,計時精確,對應用程式、訊息沒有特別的要求。System.Timers.Timer還可以應用於WinForm,完全取代上面的Timer控制項。它們的缺點是不支援直接的拖放,需要手工編碼。

例:
使用System.Timers.Timer類
//執行個體化Timer類,設定間隔時間為10000毫秒;
System.Timers.Timer t = new System.Timers.Timer(10000);
//到達時間的時候執行事件;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
t.AutoReset = true;//設定是執行一次(false)還是一直執行(true);
t.Enabled = true;//是否執行System.Timers.Timer.Elapsed事件;

====================================

自己寫的一個用System.Timer類的方法

 public class BF_CheckUpdate
      {
          private static object LockObject = new Object();
  
          // 定義資料檢查Timer
          private static Timer CheckUpdatetimer = new Timer();
  
          // 檢查更新鎖定
          private static int CheckUpDateLock = 0;
 
         ///
         /// 設定資料檢查Timer參數
         ///
         internal static void GetTimerStart()
         {
             // 迴圈間隔時間(10分鐘)
             CheckUpdatetimer.Interval = 600000;
             // 允許Timer執行
             CheckUpdatetimer.Enabled = true;
             // 定義回調
             CheckUpdatetimer.Elapsed += new ElapsedEventHandler(CheckUpdatetimer_Elapsed);
             // 定義多次迴圈
             CheckUpdatetimer.AutoReset = true;
         }
 
         ///
         /// timer事件
         ///
         ///
         ///
         private static void CheckUpdatetimer_Elapsed(object sender, ElapsedEventArgs e)
         {
            // 加鎖檢查更新鎖定
             lock (LockObject)
             {
                 if (CheckUpDateLock == 0) CheckUpDateLock = 1;
                 else return;
             }         
           
            //More code goes here.
           //具體實現功能的方法
            Check();
               // 解鎖更新檢查鎖
             lock (LockObject)
             {
                 CheckUpDateLock = 0;
             }            
         }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.