Gear.Turbo

.Net中Timers的学习备忘二

前一篇的备忘记录到了System.Timers.Timer, 本篇将继续第三个Timer也是最推荐使用的Timer:System.Threading.Timer。

要点四:

  • 不同于前面的两个Timer,System.Threading.Timer, 既没有一个Interval属性,也没有Start和Stop方法,也没有事件可以用来注册。这些相应的设置都放在了构造函数里,也就是说通过构造函数用户需要告诉Timer多长时间以后开始执行;period(即Interval)是多少,调用的Callback等。
  • 前述的Callback会在System.Threading.Timer的工作线程中被调用,因此用户应该注意线程安全的问题。
  • System.Threading.Timer被构造之后,用户仍然可以通过Change函数来设置它的启动时间和循环时间间隔。当把启动时间设成Timeout.Infinite之后,Timer便停止工作。

要点五:

  • 在多线程程序中,控件的访问是一个要注意的问题。Control.InvokeRequired属性可以用来判断当前线程是否能访问该控件。下面的示意代码显示了一个在线程中访问控件的常用模式:

要点六:

  • 要留意事件的可重入性(Reentrance),是指在事件处理函数的运行时长大于Timer周期的时候,就发生了多个事件处理函数同时运行的状态,这就有可能造成它们所共享的变量返回错误值的情况。
  • 在读原文章代码时碰到了一个Interlocked类,从来没用过,mark一下。

最后拷贝一下原文中关于三个Timer的对比表:

  

System.Windows.Forms

System.Timers

System.Threading

Timer event runs on what thread?

UI thread

UI or worker thread

Worker thread

Instances are thread safe?

No

Yes

No

Familiar/intuitive object model?

Yes

Yes

No

Requires Windows Forms?

Yes

No

No

Metronome-quality beat?

No

Yes*

Yes*

Timer event supports state object?

No

No

Yes

Initial timer event can be scheduled?

No

No

Yes

Class supports inheritance?

Yes

Yes

No

* Depending on the availability of system resources (for example, worker threads)

posted on 2010-01-06 23:38  lsp  阅读(223)  评论(0编辑  收藏  举报

导航