【发布时间】:2011-12-07 01:41:10
【问题描述】:
在查看Timer documentation 时,我遇到了以下带有此评论的示例:
// Normally, the timer is declared at the class level,
// so that it stays in scope as long as it is needed.
// If the timer is declared in a long-running method,
// KeepAlive must be used to prevent the JIT compiler
// from allowing aggressive garbage collection to occur
// before the method ends. You can experiment with this
// by commenting out the class-level declaration and
// uncommenting the declaration below; then uncomment
// the GC.KeepAlive(aTimer) at the end of the method.
//System.Timers.Timer aTimer;
code in between
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);
这是否意味着允许 C# 中的 GC 对局部变量进行垃圾收集,即使它会产生副作用?大概是因为之后我不再访问计时器,GC 可以更早地收集它?
如果我理解正确,我不确定我是否喜欢这种优化(但我可能不喜欢;))
【问题讨论】:
-
当 GC 确定 nothing outside a finalizer would notice the object's destruction 时,对象有资格被收集。
-
@Raymond 谢谢,遗憾的是无法将评论标记为正确答案:-)
标签: c# garbage-collection gc-roots