gpt4 book ai didi

c# - GC 根和局部变量

转载 作者:行者123 更新时间:2023-11-30 12:15:02 25 4
gpt4 key购买 nike

同时查看 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 可能会在作用域结束前收集局部变量,在最后一次使用变量后立即收集。将 GC.KeepAlive 放在方法的末尾可确保变量在调用 KeepAlive 之前一直处于“事件”状态。

C# 是命令式语言,因此 GC 并未设计为了解任何副作用。

关于c# - GC 根和局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8409398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com