不要Timer对象获得GC-ED在没有其他对象引用他们呢? [英] Do Timer object get GC-ed when no other object references them?

查看:172
本文介绍了不要Timer对象获得GC-ED在没有其他对象引用他们呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以含有活性计时器对象( System.Timers.Timer )被垃圾收集,如果没有其他对象引用它?

Can an object containing an active Timer (System.Timers.Timer) be garbage collected, if no other object is referencing it?

推荐答案

有一个计时器保持引用,即使你不存储某处参考两种基本方式:

There are two basic ways that a Timer stays referenced even if you don't store a reference somewhere:


  • 只要定时器。有实际产生事件的潜在System.Threading.Timer。在CLR保持活动的定时器的列表,它们的回调委托对象保持引用的定时器。

  • As long as the timer is enabled. There's an underlying System.Threading.Timer that actually generates the event. The CLR keeps a list of active timers, the callback delegate object of them keeps the Timer referenced.

通过经过的事件处理程序,如果它不是一成不变的。该定时器实例的生命周期延伸到包含Elapsed事件处理程序中的类对象的至少所述寿命

By the Elapsed event handler if it is not static. That extends the lifetime of the Timer instance to at least the lifetime of the class object that contains the Elapsed event handler.

这里没有失败的模式。唯一可能的方式来获得一个参考回到计时器通过经过的事件处理程序的发送的参数。如果禁用计时器则不再有一种方式来获得一个参考,因此它是适当的要收集的对象。

There is no failure mode here. The only possible way to get a reference back to the timer is through the Elapsed event handler's sender argument. If you disable the timer then there is no longer a way to get a reference so it is appropriate for the object to be collected.

一个相当经典的方式惹上麻烦与此定时器和失去经过的事件是当你有自动复位属性设置为false。一个很讨厌的问题是,在经过的事件处理程序引发的任何异常都没有任何诊断吞噬。这将绕过你不得不重新启动在年底计时器呼叫。不要青睐System.Threading.Timer,它没有这个问题。

A fairly classic way to get in trouble with this Timer and lose Elapsed events is when you have the AutoReset property set to false. A very nasty issue is that any exceptions raised in the Elapsed event handler are swallowed without any diagnostic. Which will bypass the call you'd have to restart the timer at the end. Do favor System.Threading.Timer, it doesn't have this problem.

这篇关于不要Timer对象获得GC-ED在没有其他对象引用他们呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆