Tech Off Thread

6 posts

On the topic of Object Immortality

Back to Forum: Tech Off
  • User profile image
    Sk4rlath

    Let's say I have the following class:

    public class Immortal
    {
        private static System.Collections.ArrayList immortals = new System.Collections.ArrayList();

        public Immortal()
        {
        }

        ~Immortal()
        {
            // rise from your grave!
            immortals.Add(this);
            System.Gc.ReRegisterForFinalize(this);
        }
    }

    If I then do the following:

    Immortal being = new Immortal();

    being = null;

    System.GC.WaitForPendingFinalizers();

    Will the program hang waiting for an immortal object to die?

    I know that the docs don't guarantee that WaitForPendingFinalizers will ever return, but I'm just curious if this will hang it.

  • User profile image
    Nrp

    I imagine immortals.Add(this) would end up throwing an exception if it was to cause some sort of loop.

  • User profile image
    Charles

    Create a console app (C#, obviously) using this algorithm, compile, run, attach the CLR Profiler to the process, inspect GC generations, answer your question.

    C

  • User profile image
    rhm

    Finalization is pretty fragile in CLR1.1 There are lots of things you can do to break the one and only finalizer thread, especially if you use synchronisation anywhere in the code.

    Obviously if you want an object to live forever you just hald a ref to it in a static variable.

  • User profile image
    amotif

    I think this practice is more commonly referred to "object resurrection." (Seriously, google it.)

  • User profile image
    cseeger

    Being the junior design patterns guy -- i'd have to suggest using a "singleton" pattern...

    -cseeger


Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.