System.Threading.Timer 是一個簡單的輕量計時器,它使用回調方法并由線程池線程提供服務。在必須更新用戶界面的情況下,建議不要使用該計時器,因為它的回調不在用戶界面線程上發生。在此類情況下,System.Windows.Threading.DispatcherTimer 是更好的選擇,因為其事件是在用戶界面線程上引發的。
多線程計時器
1:System.Threading.Timer
2:System.Timers.Timer
特殊目的的單線程計時器:
1:System.Windows.Forms.Timer(Windows Forms Timer)
2:System.Windows.Threading.DispatcherTimer(WPF timer);
多線程計時器比較強大,精確,而且可擴展性強;
單線程計時器比較安全,對于更新 Windows Forms controls或者WPF這種簡單任務來說更方便。
實現了Component,所以可以在設計器顯示。代替Change方法的一個Interval屬性代替callback委托的一個Elapsed事件啟動和停止timer的Enabled屬性,默認是false。為了避免Enabled造成混亂,提供了Start和Stop方法。是否在每次指定的間隔結束時引發Elapsed時間,還是僅間隔第一次結束后運行的AutoReset屬性。在WPF或Windows Forms中安全的調用方法的SynchronizingObject對象。publicstaticvoidMainThread()
staticvoidtmr_Elapsed(objectsender,ElapsedEventArgse)
{
Console.WriteLine("Tick...");
}
單線程計時器是被設計成屬于他們執行環境的計時器,如果你在一個Windows服務應用程序中使用Windows Forms的Timer,timer 事件并不會被觸發,只有在對應的環境下才會被觸發。
像System.Timers.Timer一樣,他們也提供了相同的成員(Interval,Tick,Start,Stop),但是他們內部的工作原理不同,
WPF和Windows Forms的計時器使用消息循環機制來取代線程池產生消息的機制。
這意味著Tick事件總是在創建timer的那個線程上執行,同時也意味著如果上一個Tick消息還未被處理,即使時間超過了間隔時間,在消息循環中也只存在一個Tick消息。
下面是它們的優點:
你可以忘記線程安全。一個Tick事件在前一個Tick事件被處理完畢前不會被觸發。你可以直接在Tick事件處理代碼中更新控件,不需要調用Control.Invoke或Dispatcher.Invoke.
看下在Winform中使用單線程定時器的效果:
publicForm1()
{
InitializeComponent();
timer.Tick+=newEventHandler(timer_Tick);
timer.Enabled=true;
}
voidtimer_Tick(objectsender,EventArgse)
{
//模擬的做一些耗時的操作
System.Threading.Thread.Sleep(2000);
}
publicForm1()
{
InitializeComponent();
timer.Elapsed+=newSystem.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled=true;
}
voidtimer_Elapsed(objectsender,System.Timers.ElapsedEventArgse)
{
//模擬的做一些耗時的操作
System.Threading.Thread.Sleep(2000);
}
上面是2種自己使用一下,感覺那個好就可以了。
新聞熱點
疑難解答