【发布时间】:2017-09-25 12:35:59
【问题描述】:
所以我知道因为问题Can Timers get automatically garbage collected?,System.Timers.Timer 不会被垃圾收集。
但我的实际问题是 - 我必须停止或处置计时器吗?
private void CreateTimer()
{
var timer = new Timer();
timer.Elapsed += TimerElapsed;
timer.Interval = 30000;
timer.AutoReset = true;
timer.Enabled = true;
}
我的意思是这个计时器将永远运行。但是现在我不再需要在方法中创建计时器的对象了。我是否必须停止或处理 Timer 以使其被垃圾收集?
【问题讨论】:
-
停止和处置是有区别的。在计时器的生命周期中,有人会需要停止计时器
-
您可以自己检查:在 Elapsed 上创建类似 MesseBox.Show 的内容,然后杀死它的所有者,例如通过关闭 subWindow。
-
我不认为它会被垃圾收集,直到你打电话给
dispose。不管你是否stop计时器。更多:Always call Dispose before you release your last reference to the Component. Otherwise, the resources it is using will not be freed until the garbage collector calls the Component object's Finalize method.msdn.microsoft.com/en-us/library/3cc9y48w(v=vs.110).aspx -
@Achilles - 不能保证有一个
Finalize方法,或者它是否写得正确,或者它是否被调用。规则应该是始终明确调用.Dispose()。 -
@Enigmativity 我同意,应该始终明确地调用
.Dispose(),但在这种情况下Timer继承自Component,它提供了`Finalize()' 的实现,所以文档是正确的。参考:msdn.microsoft.com/en-us/library/az5741fh(v=vs.110).aspx
标签: c# timer garbage-collection