Resurrection difference in using Object Initializer

后端 未结 2 1239
独厮守ぢ
独厮守ぢ 2020-12-07 02:11

I have this code:

Essentially i\'m trying to demonstrate the use of the c# finalizer and make an object that cannot die, I called it Zombie. Now, normally this demo

相关标签:
2条回答
  • 2020-12-07 02:32

    EDIT: While the original answer below is still accurate, it looks like it's the mixture of debug information and optimization which makes a difference here.

    From my experiments:

    Compiler flags                        Result
    /o+ /debug-                           Finalizer runs
    /o+ /debug+                           Finalizer runs
    /o- /debug-                           Finalizer runs
    /o- /debug+                           Finalizer does *not* run
    

    The finalizer is still called on my box, when compiling on the command line with /o+. My guess is that you're running in a debugger - which changes the GC behaviour. Without the debugger, the GC will collect anything that it can prove will never be read. With the debugger, I believe the GC won't collect any objects which still have references on the stack, even if there's no code to read the variables in question.

    Now with an object initializer, the compiler code includes an extra reference on the stack. This line:

    Zombie z = new Zombie { Name = "Guy" };
    

    is effectively:

    Zombie tmp = new Zombe();
    tmp.Name = "Guy";
    Zombie z = tmp;
    

    The assignment to z is only performed after all the properties have been set.

    My guess is that the tmp variable here is keeping the object alive.

    0 讨论(0)
  • 2020-12-07 02:40

    If you want objects that don't die, you really don't need to mess with finalizers. Just have a private static list of all instances, and add objects to that list as they are created:

    class Immortal
    {
        static List<Immortal> _immortals = new List<Immortal>();
    
        public Immortal()
        {
           _immortals.Add(this);
        }
    }
    
    0 讨论(0)
提交回复
热议问题