使用System.Threading.Timer的误区

最近一个项目大量使用多线程技术,System.Threading.Timer这个轻量级的Timer自然用得不少,到后来我养成了个不好的习惯:使用System.Threading.Timer来做异步调用。代码如下:

 

Code

结果到测试时不时出现莫名其妙的错误,最明显的就是有的时候异步操作没有被调用。找了很久,怀疑到这个Timer上,显然这个Timer对象没有引用存在,很可能成为了垃圾收集的对象。将所有这种写法改用ThreadPool后,问题解决。更改后代码如下:

Code
后查询MSDN,在System.Threading.Timer类的介绍中看到:

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

证明推想是正确的。

 

posted on 2009-08-31 23:22  Gildor Wang  阅读(966)  评论(1)    收藏  举报

导航