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定時器的用法。
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;
}
}
}
實現的效果是:每秒彈出係統當前時間,如下圖:

最後更新:2017-04-03 05:39:30