Are child objects still alive when Object.Finalize

2019-07-15 19:33发布

问题:

Say, I have this class:

class Test
{
    readonly object _child = new Object();

    // ...

    ~Test()
    {
        // access _child here
        // ...
    }
}

Is the _child object guaranteed to still be alive when ~Test is called by the garbage collector? Or should I first "pin" the _child with GCHandle.Alloc in the constructor?

回答1:

Being a readonly field _child you can't lose its reference (unless you set it to null via reflection). Which means that till the Test is garbage collected _child will stay in memory for sure.

Also, you're using a Finalizer which is called prior to garbage collection, Only on next pass the object's memory will be reclaimed, at this point _child will be alive. In other words when Finalize method is called _child will be alive and safe to access it.

Finalizer gets called doesn't mean memory will be reclaimed, If you do something like the following Finalize will be called but memory will not be reclaimed

class Test
{
    readonly object _child = new Object();

    private static Test evilInstance;

    ~Test()
    {
        evilInstance = this;//Do something crazy
        //This resurrects this instance, so memory will not be reclaimed.
    }
}

Finalizers are almost never needed when you're dealing with managed code, It adds extra work to the garbage collector and also strange things can happen as we seen above.

Update: If you use _child only for lock it is safe to use, because the _child instance will not be null, which means it points to a valid reference. Monitor.Enter and Monitor.Exit just cares about the references it is absolutely safe to use it(only for locking).

What if you need the child's Finalizer to be called only after Test's Finalizer is called?

There is a workaround: You can inherit the Child class from SafeHandle and that does the trick. It will make sure if both Test and Child goes out of scope at the same time, It will call Test's finalizer first as the Child inherits from SafeHandle which delays its finalization. But, IMO don't depend on this. Because other programmers work with you may not be knowing this which leads to misconception.

This critical finalizer also has a weak ordering guarantee, stating that if a normal finalizable object and a critical finalizable object become unreachable at the same time, then the normal object’s finalizer is run first

Quote from SafeHandle: A Reliability Case Study



回答2:

The most adequate explanation so far IMHO can be found here (see Karlsen's answer), and so to summarize an answer to the OP:

Any reachable (child or external) object during finalization of an object will still be available in memory, but the state of such an object will depend on whether this object has already been finalized itself - as there is no specific order of finalization between objects in the finalization queue.

In short, quoting from the posting:

You can not access any objects your object refer to, that has finalizers, as you have no guarantee that these objects will be in a usable state when your finalizer runs. The objects will still be there, in memory, and not collected, but they may be closed, terminated, finalized, etc. already.

You can however, use any other reachable object (with no finalization) safely during an object's finalization stage, e.g. a string. In practical terms this means it is safe to use any reachable object that does NOT implement the IDisposable interface.



回答3:

I created a simple test:

using System;

namespace ConsoleApplication1
{
    class Program

    {
        class Child
        {
            public override string ToString()
            {
                return "I am a child!";
            }

            ~Child()
            {
                Console.WriteLine("Child finalized");
            }
        }

        class Test
        {
            readonly object _child = new Child();
            readonly WeakReference _ref;

            public Test()
            {
                _ref = new WeakReference(_child);
            }

            // ...

            ~Test()
            {
                Console.WriteLine("Test finalized, child: " 
                    + _child.ToString() + ", is alive: " 
                    + _ref.IsAlive);
            }
        }

        static void Main(string[] args)
        {
            var test = new Test();
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            Console.ReadLine();
        }
    }
}

The output (Release build):

Child finalized
Test finalized, child: I am a child!, is alive: False

Thus, the _child gets finalized first. So, I need to do GCHandle.Alloc(_child) in the constructor, and do GCHandle.Free in the finalizer, after I'm done with _child.

To answer the comment why I need all of this: _child is referenced in a method which is called from the finalizer to access an unmanaged resource. That method does lock (_child) { ... } and it can be called from outside the finalizer, too.