IDisposableSnippet
IDisposable pattern.
Syntax:
C#
[field: NonSerialized] private bool _Disposed; [field: NonSerialized] private bool _IsDisposing; [field: NonSerialized] private object _DisposeLock; /// <summary>Occurs when <see cref="IDisposable.Dispose"/>d.</summary> [field: NonSerialized] public event EventHandler Disposed; /// <summary>Occurs when this object is about to be disposed.</summary> [field: NonSerialized] public event EventHandler Disposing; /// <summary>Gets a value indicating whether this object has been disposed of.</summary> [System.ComponentModel.Browsable(false)] public bool IsDisposed { get { return _Disposed; } } /// <summary>Gets a value indicating whether this object is in the process of being disposed.</summary> [System.ComponentModel.Browsable(false)] public bool IsDisposing { [System.Diagnostics.DebuggerStepThrough] get { return _IsDisposing; } [System.Diagnostics.DebuggerStepThrough] protected set { _IsDisposing = value; } } /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [System.Diagnostics.DebuggerStepThrough] void IDisposable.Dispose() { this.Dispose(); } protected virtual void Dispose(bool disposing) { if (disposing) { // check against already-disposed as an atomic CPU action: if (System.Threading.Interlocked.Equals(_Disposed, true)) { return; } // create the dispose-lock as an atomic action (if it doesn't already exist): System.Threading.Interlocked.CompareExchange<object>(ref _DisposeLock, new object(), null); lock (_DisposeLock) { _IsDisposing = true; OnDisposing(); // your disposing code here... _Disposed = true; _IsDisposing = false; OnDisposed(); } } } /// <summary>Raises the <see cref="Disposed"/> event.</summary> protected void OnDisposed() { EventHandler handlers = this.Disposed; if (handlers != null) { handlers(this, EventArgs.Empty); } } [field: NonSerialized] private bool _OnDisposingRaised; /// <summary>Raises the <see cref="Disposing"/> event.</summary> protected void OnDisposing() { if (_OnDisposingRaised) { return; } EventHandler handlers = this.Disposing; if (handlers != null) { handlers(this, EventArgs.Empty); } _OnDisposingRaised = true; }