C#中Timer定時器的使用樣本

來源:互聯網
上載者:User

關於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控制項。它們的缺點是不支援直接的拖放,需要手工編碼。

本文URL:http://www.bianceng.cn/Programming/csharp/201410/45596.htm

下面舉例說明,System.Timers.Timer定時器的用法。

using System;  using System.Collections.Generic;  using System.ComponentModel;  using System.Data;  using System.Drawing;  using System.Linq;  using System.Text;  using System.Windows.Forms;  using System.Timers;  using System.Runtime.InteropServices;  using System.Threading;        namespace Timer001  {      public partial class Form1 : Form      {          public Form1()          {              InitializeComponent();                           }          //執行個體化Timer類          System.Timers.Timer aTimer = new System.Timers.Timer();                      private void button1_Click(object sender, EventArgs e)          {              this.SetTimerParam();          }                private void test(object source, System.Timers.ElapsedEventArgs e)          {                   MessageBox.Show(DateTime.Now.ToString());                     }                public void SetTimerParam()          {              //到時間的時候執行事件              aTimer.Elapsed += new ElapsedEventHandler(test);              aTimer.Interval = 1000;              aTimer.AutoReset = true;//執行一次 false,一直執行true              //是否執行System.Timers.Timer.Elapsed事件              aTimer.Enabled = true;          }      }  }

實現的效果是:每秒彈出系統目前時間,如下圖:

聯繫我們

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