DisposableBase.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. namespace Wayne.Lib
  3. {
  4. /// <summary>
  5. /// Utility Base class that manages the disposable pattern.
  6. /// Note that it only invokes the DoDispose when called from
  7. /// explicit Dispose call. If called from finalizer, this is not called.
  8. /// </summary>
  9. public abstract class DisposableBase : IDisposable
  10. {
  11. private readonly object disposedLock = new object();
  12. private bool disposed;
  13. private bool disposeRunning;
  14. ~DisposableBase()
  15. {
  16. Dispose(false);
  17. }
  18. public void Dispose()
  19. {
  20. Dispose(true);
  21. GC.SuppressFinalize(this);
  22. }
  23. private void Dispose(bool disposing)
  24. {
  25. if (disposing)
  26. {
  27. lock (disposedLock)
  28. {
  29. if (disposed || disposeRunning)
  30. {
  31. return;
  32. }
  33. disposeRunning = true;
  34. }
  35. try
  36. {
  37. DoDispose();
  38. }
  39. finally
  40. {
  41. lock (disposedLock)
  42. {
  43. disposed = true;
  44. disposeRunning = false;
  45. }
  46. }
  47. }
  48. }
  49. protected bool IsDisposed
  50. {
  51. get { return disposed || disposeRunning; }
  52. }
  53. /// <summary>
  54. /// Method that
  55. /// </summary>
  56. protected abstract void DoDispose();
  57. }
  58. }