C#三種定時器

關於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類,這個簡單好用

System.Timers.Timer t = new System.Timers.Timer(10000);//實例化Timer類,設置間隔時間爲10000毫秒;

t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到達時間的時候執行事件;

t.AutoReset = true;//設置是執行一次(false)還是一直執行(true);

t.Enabled = true;//是否執行System.Timers.Timer.Elapsed事件;



public void theout(object source, System.Timers.ElapsedEventArgs e)

{

MessageBox.Show("OK!");

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章