.net框架中计时器(Timer)的这些事

.net的基础库提供了4个类别的计时器,使用的时候经常搞混,为了更好的使用这几个计时器,把每个的情况整理如下:

类别

说明

使用场景

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”

posted @ 2011-05-03 17:25  2012  阅读(2040)  评论(1编辑  收藏  举报