在查看Timer 文档时,我遇到了以下带有此注释的示例:
// 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 可以更早地收集它?
如果我正确理解这一点,我不确定我是否喜欢这种优化(但我可能不会;))