Why does the garbage collector take objects in the wrong order?

I have an application with two classes: A and B. Class A contains a reference to class B. Class destructors do some cleanup of resources, but they need to be called in the correct order, first the destructor A, and then the destructor B.

What happens is that one way or another, the destructor B is called first, and then destroys the destructor A, because it is trying to execute methods from the located object.

Is this GC behavior right? I expected the GC to detect that A has a reference to B, and then first call the destructor of A. Am I right?

Thank you comrades!

PD: In case of doubt regarding the destructor / finalizer / deletion, etc. that we have:

~A()
{
    this.Dispose();
}

~B()
{
    this.Dispose();
}    
+5
5

GC : - - - - , . , .

, IDisposable.

+12

, , , . Dispose , . .

- , , . , , :

  • ( ) . , , , , , ..

  • "" , , . . .

  • , , . , , , .

. , , .

+13

http://msdn.microsoft.com/en-us/magazine/bb985010.aspx:

, Finalize. , , , . , . , , Finalize . Finalize , , . , Finalize - -.

+9

, #, , .

+2

- , , , , , .

, , , " ". , , , , .

In any case, here you must implement the finalizer. Note that you only need to implement the finalizer if you need to destroy unmanaged resources (note: there are some extreme cases when you can use the finalizer for a special class, but I will not mention it more than this here):

public class Test : IDisposable
{
    ~Test()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        // TODO: Make sure calling Dispose twice is safe
        if (disposing)
        {
            // call Dispose method on other objects
            GC.SuppressFinalize(this);
        }

        // destroy unmanaged resources here
    }
}

Further information can be found here: Implementation of the removal method .

+1
source

All Articles