When to dispose objects? C#

Viewed 319

I wrote a for-loop that inside of it I declared a new Image, so should I Dispose it every time inside the internal for-loop, or once it is all finished, and what's the difference?

Here's an example to make things clear, Should I use this:

for (int i = 0; i < 10; i++)
{
    Image imgInput = new Image();

    for (int j = 0; j < 100; j++)
    {
        // Here is a code to use my image

        Image.Dispose();
    }
}

OR:

for (int i = 0; i < 10; i++)
{
    Image imgInput = new Image();

    for (int j = 0; j < 100; j++)
    {
        // Here is a code to use my image
    }

    Image.Dispose();
}
2 Answers

We usually wrap IDisposable into using in order to guarantee that the instance (i.e. unmanaged resources) will be disposed rain or shine. If you want to declare Image outside of the inner loop:

for (int i = 0; i < 10; i++)
{
    using (Image imgInput = new Image()) 
    {
        for (int j = 0; j < 100; j++)
        {
            ...
            // In all these cases the resource will be correctly released: 

            if (someCondition1) 
                break;

            ...

            if (someCondition2) 
                return;

            ...

            if (someCondition3) 
                throw new SomeException(...);

            ...  
            // Here is a code to use my image
        }
    }
}

That's why, we should not call Dispose explicitly. Please note, that both code excerpts you've provided will result in resource leakage in case of someCondition2 or someCondition3.

Same scheme if you want to declare Image within the nested loop:

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 100; j++) 
    {
        using (Image imgInput = new Image()) 
        {
            // Here is a code to use my image
        }        
    }     
}

If you don't calls your dispose method the destructor (finalizer) is responsible for freeing the resources. The GC only cleans up managed resources. Calling Bitmap.Dispose allows you to ensure that these unmanaged resources are cleaned up in a timely manner and that you aren't leaking resources.

Typically in your case destructor will be called if it will goes out of the scope.

Always call Dispose before you release your last reference to the Image. Otherwise, the resources it is using will not be freed until the garbage collector calls the Image object's Finalize method.

Your second method makes sense. You will dispose it after using the image object.

for (int i=0;i<10;i++)
{
    Image imgInput = new Image();
    for (int j=0;j<100;j++)
    {
        //Here is a code to use my image
    }
    Image.Dispose();
}

Call Dispose when you are finished using the Image. The Dispose method leaves the Image in an unusable state. After calling Dispose, you must release all references to the Image so the garbage collector can reclaim the memory that the Image was occupying.

Related