How can I track where IDisposable objects flowed from?

I recently debugged some code that was a bit lost. This is a long program that runs as a Windows service.

If you find a class that has an interface IDisposable, it tells you that some of the resources it uses are outside the scope of the garbage collector to clean you up.

The reason you say this is because you, the user of this object, are now responsible for clearing these resources. Congratulations!

As a conscientious developer, you are pushing for a method call .Dispose()when you are done with an object to free these unmanaged resources.

There is a good template using()that will help clear these resources after they are completed. Which only leaves detection of which objects cause leakage?

To help keep track of these unmanaged rogue resources, is there any way to query which objects loitering around waiting to be Disposed at any given time?

+3
source share
9 answers

There should be no cases where you do not want to call Dispose, but the compiler cannot tell you where , you should call dispose.

Suppose you write a factory class that creates and returns one-time objects. Should a compiler error not cause you to Dispose when the cleanup should be responsible for your subscribers?

+6

IDisposable using. , Dispose() - , , :

class A : IDisposable {}

/// stuff

using(var a = new A()) {
  a.method1();
}

Dispose().

+4

" , loitering , Disposed?"

, , CLR , , IDisposable , Dispose(). .

, , , IDiposable- , . Dispose(), , -, , .

+3

Dispose. IDisposable - , , , , , , , GC . AFAIK Dispose , using.

+1

.NET 2.0 Ping, . , Dispose . , - , Ping IDisposable, Dispose() ( ).

private void Refresh( Object sender, EventArgs args )
{
    Ping ping = null;

    try
    {
        ping = new Ping();
        ping.PingCompleted += PingComplete;
        ping.SendAsync( defaultHost, null );
    }
    catch ( Exception )
    {
        ( (IDisposable)ping ).Dispose();
        this.isAlive = false;
    }
}

private void PingComplete( Object sender, PingCompletedEventArgs args )
{
    this.isAlive = ( args.Error == null && args.Reply.Status == IPStatus.Success );
    ( (IDisposable)sender ).Dispose();
}
+1

, , , IDisposable? , - , ( "" ).

, , , . - windbg sos.dll; , , . ( "" ) Red Hat ANTS Profiler, - .

: Dispose - . , - , "" ( ) , . GC.

+1

, , .

0

, / (, factory) /, ? , . , - , Dispose .

0

, Dispose() - , , . . , , , FxCop StyleCop, , , , Spe#/Sing #. , , , " .Dispose() - ".

I'm honestly not sure if there are any static analyzers that can check if .Dispose () is being called. Even for static analysis, as it exists today, this may be a little too subjective. However, if you need a place to start your search, "Static Analysis for C #" is probably the best place.

0
source

All Articles