Search code examples
c#garbage-collectiondisposefinalize

Dispose/finalize pattern : disposing managed ressources


Let's imagine I have a class named Base with 3 attributes :

class Base : IDisposable
{
    private string _String;
    private Class1 classe1;
    private int foo;

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    public virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            Console.WriteLine("Free Managed ressources");
                  //HOW TO FREE _String, class1 and foo ?!          
        }
        Console.WriteLine("Free unmanaged ressources");
    }

    ~Base()
    {
        this.Dispose(false);
    }
}

and a classe named Class1 with 2 attributes :

class Class1
{
    public int entier { get; set; }
    public string Nom { get; set; }
}

My question is : How can I free the attributes of Base in the Dispose method ? (_String, classe1, foo)


Solution

  • My question is : How can I free the attributes of Base in the Dispose method ? (_String, classe1, foo)

    You don't need to, that's the job of the garbage collector. Implementing IDisposable is a way for the framework to let you release any unmanaged resources you have allocated, and dispose managed objects implementing IDisposable themselves (which in turn hold other unmanaged resources).

    None of the managed objects at your disposable implement IDisposable, and they will be collected once there is no longer any objects pointing to your Base class. When will that happen? In an arbitrary time, when the GC see's that there is no longer space in generation 0, and it needs to collect. There is nothing you need to do.

    Implementing IDisposable does not mean "this object will be collected immediatly once i run Dispose()", it merely means that the framework gives you a chance to reclaim any resources it might not be aware of (such as unmanaged ones). It is a recommended approach, if one implements a finalizer, to suppress the call to it via GC.SuppressFinalize, saving the GC the trouble of moving your object from the Finalizer Queue to the F-Reachable Queue, hence making it available for collection earlier.

    when will these 3 attributes free from the heap ? The garbage collector won't free them because I have GC.SuppressFinalize(this)

    You have a basic misunderstanding of how the GC works and what SuppressFinalize means. The GC will run at an non-deterministic time, and you basically shouldn't care when that happens. It's his responsibility to clean up after you. Calling SuppressFinalize on an object implementing a finalizer does nothing more than set a bit in the objects header which the runtime checks when calling finalizers, which will suppress your finalizer from running