Gorgo.Live.ToString()

Mariusz, Gorzoch tech Blog

Proper construction of classes which need to release they child objects

leave a comment »

Each time when I need to write a class which need to work with some COM objects I reinvent the wheel be finding out what should be a proper construction class. This time I wanted to put this in one place so I’ll have reference to that. Ok, so what is the proper class construction ? Take look here:

class Test : IDisposable
{
    #region IDisposable Members

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

        CleanUp(true);
    }

    #endregion

    private void CleanUp(bool codeDispose)
    {
        if (codeDispose)
        {
            //dispose called in code not by GC
        }

        //Perform resource clean-up here
        // for example relese you all COM Objects
    }

    ~Test()
    {
        CleanUp(false);
    }
}

This construction have to ways of releasing objects. First one is “Dispose” mechanism. If developer will use disposal method to release object resources then those resources will be released when he want. Second one is done thru destructor of the class. Inside destructor we are calling “CleanUp” method and by this releasing object. Someone can ask what for we need “Dispose” mechanism if destructor way do not depend on the developer and also is doing his job. The answer is simple : in case of the “Destructor” we are rallying on special “Thread” use by .Net to call our destructor. In addition to that, we need to know that this special Thread will call our destructor method when GC will perform his clean-up work and move our object to higher generation. This process consume much more resources then the one with use of “Dispose” method, so whatever you can use “Dispose” mechanism.

here is some reference, which is quite good overview of the problem : http://www.red-gate.com/products/ants_memory_profiler/DOTNET_Memory_Management/Index.html

Advertisements

Written by Mariusz Gorzoch

29 September 2009 at 09:58

Posted in Bez kategorii

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: