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

 

, Timeout.Infinite);

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

 (_syncRoot)
    {
        handle (p);
    }
}, param);
后查询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.

证明推想是正确的。

 

相关文章:

  • 2022-12-23
  • 2022-01-26
  • 2023-02-06
  • 2021-10-20
  • 2021-12-31
  • 2021-09-25
  • 2021-10-15
猜你喜欢
  • 2021-08-30
  • 2022-12-23
  • 2021-09-27
  • 2022-12-23
  • 2022-01-16
  • 2022-12-23
相关资源
相似解决方案