Advertisement
bobmarley12345

Thread safe c# disposable class

May 13th, 2023
731
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.71 KB | None | 0 0
  1. public abstract class Disposable : IRealDisposable {
  2.     private volatile int isDisposed;
  3.     public bool IsDisposed {
  4.         get => this.isDisposed != 0;
  5.     }
  6.     protected Disposable(bool canDisposeInDestructor = true) {
  7.         if (!canDisposeInDestructor) {
  8.             GC.SuppressFinalize(this);
  9.         }
  10.     }
  11.     ~Disposable() {
  12.         this.Dispose(false);
  13.     }
  14.     public void Dispose() {
  15.         this.Dispose(true);
  16.     }
  17.     public void Dispose(bool isDisposing) {
  18.         if (Interlocked.CompareExchange(ref this.isDisposed, 1, 0) != 0)
  19.             return;
  20.         GC.SuppressFinalize(this);
  21.         this.OnDispose(isDisposing);
  22.     }
  23.     protected abstract void OnDispose(bool isDisposing);
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement