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);
}
}