/* Disposable.cs Copyright (c) 2007-2008 Chris Peterson (cpeterso@cpeterso.com) Version History: 2008-01-18 = finalizer exceptions are ignored, so debug break instead 2008-01-09 = minor clean up 2007-10-23 = initial public release MIT LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // #define DISPOSABLE_BREAK_ON_LEAK using System; using System.Diagnostics; namespace cp { public abstract class Disposable : IDisposable { [Conditional("DEBUG")] public static void DumpMemoryLeaks() { #if DEBUG // run finalizers to find disposable objects that have been leaked (i.e. not disposed) GC.Collect(); GC.WaitForPendingFinalizers(); // any more finalizers to be run? GC.Collect(); GC.WaitForPendingFinalizers(); #endif // DEBUG } protected Disposable() { } public bool Disposed { get { return _disposed; } } public void Dispose() { if (_disposed) { return; // already disposed } // call the derived class's Dispose(bool disposing) method Dispose(true); } protected virtual void Dispose(bool disposing) { // called when the derived class's Dispose(bool disposing) calls base.Dispose(disposing) if (!disposing) { throw new InvalidOperationException("object expected to be disposed, not finalized"); } if (_disposed) { throw new ObjectDisposedException(ClassName); } _disposed = true; GC.SuppressFinalize(this); } #if DEBUG ~Disposable() { // finalizer is only called if our Disposable.Dispose(bool disposing) did not get called! string reason = _disposed ? "Did your derived class forget to call base.Dispose(disposing)?" : "Did you forget to Dispose() this object?"; string warning = String.Format("LEAK! {0} not disposed. {1}", ClassName, reason); Console.WriteLine(warning); #if DISPOSABLE_BREAK_ON_LEAK Debugger.Break(); #endif // DISPOSABLE_BREAK_ON_LEAK } #endif // DEBUG private string ClassName { get { return string.Format("{0}", this); } } private bool _disposed; } }