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

本文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;   
      
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;  
        }  
    }  
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM