Why call GC.KeepAlive at the end, not at the beginning?

From GC.KeepAlive() on MSDN :

Link this method at the end, and not at the beginning, of the range of instructions in which obj should be available.

Why does this have such unintuitive behavior?

+6
source share
1 answer

Since otherwise, technically, the JIT and CLI could determine that the value is not used after this point, and consider an object that is viable for collection. Heck, the compiler may decide to completely remove the variable and simply "pop out" of the stack after the last use.

Note that GC.KeepAlive does virtually nothing . This is an opaque no-op method. The fact is that if you call an opaque method with an object as a parameter, this object should still be around , that is, reachable, that is, not assembled.

This is where KeepAlive is implemented (with some uninteresting attributes):

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

Source: https://habr.com/ru/post/958485/


All Articles