.NET logo

tracking IDisposable instances

home | software | utility classes | tracking IDisposable instances

By implementing IDisposable in your type, you're specifying a usage contract that indicates you have resources of some description that must be tidied up. If those resources are unmanaged, you may be defending against memory leaks. If those resources are threads, you may be ensuring the application will end gracefully. Unfortunately, there's no way to guarantee that users of your class (including yourself!) will dispose of your object as you intended.

Enter DisposableHelper.cs: a simple utility class that will identify when an instance of your type has not been disposed when the process or AppDomain exits.

This class uses the Conditional attribute, telling the compiler only to include calls to the Register and Unregister methods when compiling in Debug mode.

using the class

An example usage, showing a simple case:

/// <summary> /// A sample object with resources that require disposal. /// </summary> public sealed class ResourceManager : IDisposable { private readonly Resource _resource; public ResourceManager() { _resource = new Resource(); // register this as an instance that requires disposal DisposableHelper.Register(this); } public void Dispose() { // notify helper class that this object has been disposed DisposableHelper.Unregister(this); } }

If an instance were to be undisposed when the process exits, and if the build type was Debug, a line would be printed in the debug output indicating that undisposed instance(s) exist. If the debugger is attached, it will break as though it hit a breakpoint, and the undisposed objects may be inspected.

This class will only help you track instances of IDisposable for which you control the code, and for which you include the two lines of code as shown above. DisposableHelper will not assist in tracking framework objects such as Brush or Stream.


submitting feedback

Please feel free to provide feedback on this class .

Authored by Drew Noakes, October 2006. Use freely, though keep this message in the source intact and report any bugs to me. I also appreciate seeing extensions, or simply hearing that you're using these classes. You may not copyright this work, though may use it in commercial/copyrighted works. Happy coding.