Why call GC.KeepAlive in the end, and not in the beginning? [duplicate]

为君一笑 提交于 2021-02-04 15:22:05

问题


From GC.KeepAlive() on MSDN:

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

Why does it have such non-intuitive behavior?


回答1:


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.

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.

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

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


来源:https://stackoverflow.com/questions/20098498/why-call-gc-keepalive-in-the-end-and-not-in-the-beginning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!