为什么要在结尾而不是在开头调用GC.KeepAlive? [英] Why call GC.KeepAlive in the end, and not in the beginning?

查看:69
本文介绍了为什么要在结尾而不是在开头调用GC.KeepAlive?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 GC.KeepAlive()在MSDN上:

From GC.KeepAlive() on MSDN:

将此方法编码在以下范围的末尾而不是开始说明 obj 必须可用.

为什么会有这种非直觉的行为?

Why does it have such non-intuitive behavior?

推荐答案

否则,由于在技术上,JIT和CLI可以确定该点之后不再使用该值,并认为该对象对于收藏.哎呀,编译器可以决定完全删除该变量,并在最后一次使用后将其从堆栈中弹出".

Because otherwise technically the JIT and CLI could determine that the value isn't used after that point, and consider the object viable for collection. Heck, the compiler could decide to remove the variable completely and just "pop" it from the stack after the last usage.

请注意, GC.KeepAlive 实际上没有执行任何操作.这是一种不透明的无操作方法.关键是,如果您使用对象作为参数调用不透明方法,则该对象仍需要保持在左右,即可访问,即不可收集.

Note that GC.KeepAlive doesn't actually do anything. It is an opaque, no-op method. The point is that if you are calling an opaque method with an object as a parameter, that object still needs to be around, i.e. reachable, i.e. non-collectable.

以下是 KeepAlive 的实现方式(已删除了一些无关的属性):

Here's how KeepAlive is implemented (with some uninteresting attributes removed):

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

这篇关于为什么要在结尾而不是在开头调用GC.KeepAlive?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆