加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么最后调用GC.KeepAlive而不是在开头?

发布时间:2020-12-15 18:22:18 所属栏目:百科 来源:网络整理
导读:参见英文答案 Understanding garbage collection in .NET3个 从 GC.KeepAlive() on MSDN开始: Code this method at the end,not the beginning,of the range of instructions where obj must be available. 为什么会出现这种非直观的行为? 解决方法 因为从
参见英文答案 > Understanding garbage collection in .NET3个
GC.KeepAlive() on MSDN开始:

Code this method at the end,not the beginning,of the range of
instructions where obj must be available.

为什么会出现这种非直观的行为?

解决方法

因为从技术上讲,JIT和CLI可以确定在该点之后不使用该值,并认为该对象可用于收集.哎呀,编译器可以决定完全删除变量,并在上次使用后从堆栈中“弹出”它.

请注意,GC.KeepAlive实际上并没有做任何事情.这是一种不透明的无操作方法.关键在于,如果您使用对象作为参数调用不透明方法,则该对象仍然需要在周围,即可到达,即不可收集.

以下是KeepAlive的实现方式(删除了一些不感兴趣的属性):

[MethodImpl(MethodImplOptions.NoInlining)]
public static void KeepAlive(object obj)
{
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读