views:

147

answers:

4

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?

+2  A: 

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.

Ngu Soon Hui
If it's not possible, how does ANTS do it?
Dan Tao
@Dan: I'm guessing via the profiling API: http://www.blong.com/Conferences/DCon2003/Internals/Profiling.htm
280Z28
@280Z28: I meant it as a rhetorical question--I'm pretty sure the fact that ANTS does it (via a .NET API, no less) means that it *is* possible. That said, I certainly wouldn't do it myself when something like ANTS already exists.
Dan Tao
+1  A: 

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

Mitch Wheat
A: 

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.

C. Ross
This *especially* applies to release builds: you should not override the finalizer for any object that doesn't *directly* hold *unmanaged* resources due to an unnecessary and significant performance overhead. Unmanaged resources should almost always be held in a class derived from `SafeHandle` (or similar) to reduce the load on the GC as well.
280Z28
A: 

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

Joe