andrew4582

DisposableObject

Feb 18th, 2012
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1.    /// <summary>
  2.     /// Abstract implementation of logic commonly required to safely handle disposable unmanaged resources.
  3.     /// </summary>
  4.     public abstract class DisposableObject:IDisposable {
  5.         private bool _disposed;
  6.         private readonly static object DisposalLock = new object();
  7.  
  8.         /// <summary>
  9.         /// Gets a value indicating whether this instance is disposed.
  10.         /// </summary>
  11.         /// <value>
  12.         ///     <c>true</c> if this instance is disposed; otherwise, <c>false</c>.
  13.         /// </value>
  14.         public bool IsDisposed {
  15.             get { return _disposed; }
  16.         }
  17.  
  18.         /// <summary>
  19.         /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  20.         /// </summary>
  21.         /// <filterpriority>2</filterpriority>
  22.         public void Dispose() {
  23.             Dispose(true);
  24.  
  25.             // Use SupressFinalize in case a subclass of this type implements a finalizer.
  26.             GC.SuppressFinalize(this);
  27.         }
  28.  
  29.         ~DisposableObject() {
  30.             // Run dispose but let the class know it was due to the finalizer running.
  31.             Dispose(false);
  32.         }
  33.  
  34.         protected virtual void Dispose(bool disposing) {
  35.             lock(DisposalLock) {
  36.                 // Only operate if we haven't already disposed
  37.                 if(IsDisposed || !disposing)
  38.                     return;
  39.  
  40.                 // Call to actually release resources. This method is only
  41.                 // kept separate so that the entire disposal logic can be used as a VS snippet
  42.                 DisposeResources();
  43.  
  44.                 // Indicate that the instance has been disposed.
  45.                 _disposed = true;
  46.             }
  47.         }
  48.  
  49.         /// <summary>
  50.         /// Handles the disposal of resources. Derived from abstract class <see cref="DisposableObject"/> which handles common required locking logic.
  51.         /// </summary>
  52.         protected abstract void DisposeResources();
  53.  
  54.         protected virtual void DisposeUnmanagedResources() {
  55.  
  56.         }
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment