当没有其他对象引用 Timer 对象时,它们是否会被垃圾回收? [英] Do Timer object get GC-ed when no other object references them?

查看:20
本文介绍了当没有其他对象引用 Timer 对象时,它们是否会被垃圾回收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有其他对象引用它,包含活动计时器 (System.Timers.Timer) 的对象是否可以被垃圾回收?

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

推荐答案

即使您没有在某处存储引用,Timer 也可以通过两种基本方式保持引用:

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

  • 只要定时器被启用.有一个实际生成事件的底层 System.Threading.Timer.CLR 保留活动计时器列表,它们的回调委托对象保留 Timer 引用.

  • 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 事件处理程序执行.这将 Timer 实例的生命周期至少延长到包含 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.

这里没有故障模式.获取对计时器的引用的唯一可能方法是通过 Elapsed 事件处理程序的 sender 参数.如果禁用计时器,则不再有获取引用的方法,因此它适合要收集的对象.

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.

遇到此计时器问题并丢失 Elapsed 事件的一种相当经典的方法是将 AutoReset 属性设置为 false.一个非常令人讨厌的问题是 Elapsed 事件处理程序中引发的任何异常都被吞下而没有任何诊断.这将绕过您必须在最后重新启动计时器的呼叫.喜欢 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 对象时,它们是否会被垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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