c# - Why an unreferenced object is not collected? -
this program prints "true" console.
allocate object, make weakreference of that, go out of block scope, , check weakreference.isalive.
public static void main (string[] args) { test (); } static void test () { weakreference wref = null; { // block scope var obj = new object (); wref = new weakreference (obj); } // obj out of scope // console.writeline (obj); gc.collect (); console.writeline (wref.isalive); // => true }
why obj not collected, though obj out of scope?
the program compiled mono 3.12.0.
edit:
sorry, inappropriate example.
the following program print true. block scope seems not related. tried not debug mode.
public static void main (string[] args) { test (); } static void test () { weakreference wref = null; var obj = new object (); wref = new weakreference (obj); obj = null; gc.collect (); console.writeline (wref.isalive); // => true }
$ mcs -debug- program.cs $ mono program.exe
you expect gc 100% deterministic, when it's not.
a few things might have happened:
- the jit optimized null assignment away.
- a pointer instance can left on in temporary stack location, or in register (you called function, passing variable, put variable in register on architectures).
Comments
Post a Comment