天天看點

.net架構中計時器(Timer)的這些事

.net的基礎庫提供了4個類别的計時器,使用的時候經常搞混,為了更好的使用這幾個計時器,把每個的情況整理如下:

<b>類别</b>

<b>說明</b>

<b>使用場景</b>

System.Threading.Timer

mscorlib (in mscorlib.dll)

要在一個線程池上執行定時的(周期性發生的)背景任務是,常用的計時器

觸發器方法在系統提供的線程池中執行(不是在建立計時器的線程)

不更新UI的情況基本都适用

System.Windows.Forms.Timer

System.Windows.Forms.dll

構造這個類的一個執行個體,相當于告訴Windows将一個計時器和調用線程關聯(Win32的SetTimer).這個計時器觸發時,Windows将一條計時器消息(WM_TIMER)插入線程的消息隊列,消息循環提取到這個消息時,執行計時器的回調函數。

注意:所有這些工作都是由一個線程完成,計時器方法不會由多個線程并發執行

Windows Form界面部分适用,在計時器觸發中可以處理界面,不需要線程的手動切換

System.Windows.Threading. DispatcherTimer

WindowsBase.dll

這個是System.Windows.Forms.Timer在Silverlight和WPF應用程式中的等價物

WPF Silverlight界面部分适用

System.Timers.Timer

System (in System.dll)

這個計時器基本上是System.Threading的Timer的一個包裝類。計時器觸發時,會導緻CLR将事件放到線程池的隊列中。這個類繼承于Component,是以可在IDE中可視化使用。

曆史遺留,一般不使用【Jeff Richter語】

不過MSDN提到這個是基于伺服器的計時器,特殊場景可用

The server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

根據以上場景,你就可以正确選擇自己的計時器了。

參考 “CLR Via C# Jeffrey Richter”