在查看计时器文档时,我发现以下示例并附有以下注释:
// 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可以更早地将其收集吗?
如果我理解正确的话,我不确定我喜欢这样的优化(但我可能并没有理解)。