Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 996
Doug Avatar asked Nov 20 '13 14:11

Doug


1 Answers

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)
{
}
like image 170
Marc Gravell Avatar answered Sep 20 '22 15:09

Marc Gravell