I need a tool to find IDisposables missing Dispose/using

N

not_a_commie

Are there any tools available to track down IDisposable objects that
don't have a call to Dispose? I'm thinking this can be done with
static code analysis. If the object is created inside a method, it
should be created with a using statement. If it's a member of a class,
that class should have a Dispose function or call Dispose on the
object somewhere in there.
 
D

Doug Semler

Are there any tools available to track down IDisposable objects that
don't have a call to Dispose? I'm thinking this can be done with
static code analysis. If the object is created inside a method, it
should be created with a using statement. If it's a member of a class,
that class should have a Dispose function or call Dispose on the
object somewhere in there.

FxCop can detect quite a few of them.
 
S

Samuel R. Neff

One mechanism I like is to add code in the finalizer to log an error
whenever a disposable object is finalized ('cause finalizer is
suppressed when dispose is called).

HTH,

Sam

------------------------------------------------------------
We're hiring! B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.




using System;
using System.Diagnostics;

namespace Common
{
public abstract class DisposableBase : IDisposable
{
private bool _isDisposed;
#if DEBUG
/// <summary>
/// Contains the stack when the object was allocated.
/// </summary>
private StackTrace _allocStack;
#endif

public event EventHandler Disposed;

protected DisposableBase()
{
#if DEBUG
_allocStack = new StackTrace();
#endif
}

#if DEBUG
~DisposableBase()
{
DisposeImpl(false);
}
#endif

public void Dispose()
{
DisposeImpl(true);
GC.SuppressFinalize(this);
}

private void DisposeImpl(bool disposing)
{
bool wasDisposed = _isDisposed;
_isDisposed = true;

try
{
#if DEBUG
if (!disposing)
{
Log.Debug(this, "Disposable object not disposed.\r\n\r\n" +
_allocStack);
}
#endif
Dispose(disposing);
if (disposing && !wasDisposed && Disposed != null)
{
Disposed(this, EventArgs.Empty);
}
}
catch (Exception ex)
{
Log.Fatal(this, "Error thrown during dispose.", ex);
}
}
protected abstract void Dispose(bool disposing);

}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top