serhio
serhio

Reputation: 28586

How do I check if my object is properly disposed?

I wonder if there a "trick" that permits to know if the used objects in a portion o code has been properly(entirely) disposed, or, in other words don't creates memory leaks.

Let's say I have a container of GDI objects (or other that I need to explicitly dispose)

public class SuperPen 
{
    Pen _flatPen, _2DPen, _3DPen;
    public SuperPen() 
    {
        _flatPen = (Pen)Pens.Black.Clone();
        _2DPen = (Pen)Pens.Black.Clone();
        _3DPen = (Pen)Pens.Black.Clone();
    }
}

Now, as I need to Dispose the GDI objects I do:

public class SuperPen : IDisposable
{
    Pen _flatPen, _2DPen, _3DPen;
    public SuperPen()
    {
        _flatPen = (Pen)Pens.Black.Clone();
        _2DPen = (Pen)Pens.Black.Clone();
        _3DPen = (Pen)Pens.Black.Clone();
    }

    public void Dispose()
    {
        if (_flatPen != null) { _flatPen.Dispose(); _flatPen = null; }
        // HERE a copy paste 'forget', should be _2DPen instead
        if (_flatPen != null) { _flatPen.Dispose(); _flatPen = null; }
        if (_3DPen != null) { _3DPen.Dispose(); _3DPen = null; }
    }
}

Situation like this can happen if you add a new "disposable" object and forget to dispose it etc. How can I detect my error, I mean, check if my SuperPen was properly disposed?

Upvotes: 5

Views: 2410

Answers (4)

to StackOverflow
to StackOverflow

Reputation: 124726

I believe FxCop (available standalone or integrated into the Team System versions of VS2005+) will detect this.

Upvotes: 0

C. Ross
C. Ross

Reputation: 31848

I would suggest using this pattern, which incorporates a destructor to ensure than un-disposed items are cleaned up. This will catch anything that you're not calling 'dispose' on, and is a good fail safe.

Upvotes: 0

Mitch Wheat
Mitch Wheat

Reputation: 300579

A tool such as MemProfiler or ANTS Memory Profiler will identify memory leaks (both have trial versions).

Upvotes: 1

Graviton
Graviton

Reputation: 83254

Don't think it is possible; the best you can do is to get a profiler (such as ants profiler) and measure it. If you find that you are leaking memory excessively ( via the profiler), then there is something wrong.

Other than using profiler, I am not sure of any automatic techniques that help you identify undisposed resources.

Upvotes: 2

Related Questions