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?
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)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With