DisposableManagedObjectBase.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. namespace Emby.Server.Implementations.Net
  3. {
  4. /// <summary>
  5. /// Correclty implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceities not on the interface such as an <see cref="IsDisposed"/> property.
  6. /// </summary>
  7. public abstract class DisposableManagedObjectBase : IDisposable
  8. {
  9. #region Public Methods
  10. /// <summary>
  11. /// Override this method and dispose any objects you own the lifetime of if disposing is true;
  12. /// </summary>
  13. /// <param name="disposing">True if managed objects should be disposed, if false, only unmanaged resources should be released.</param>
  14. protected abstract void Dispose(bool disposing);
  15. //TODO Remove and reimplement using the IsDisposed property directly.
  16. /// <summary>
  17. /// Throws an <see cref="ObjectDisposedException"/> if the <see cref="IsDisposed"/> property is true.
  18. /// </summary>
  19. /// <seealso cref="IsDisposed"/>
  20. /// <exception cref="ObjectDisposedException">Thrown if the <see cref="IsDisposed"/> property is true.</exception>
  21. /// <seealso cref="Dispose()"/>
  22. protected virtual void ThrowIfDisposed()
  23. {
  24. if (IsDisposed) throw new ObjectDisposedException(GetType().Name);
  25. }
  26. #endregion
  27. #region Public Properties
  28. /// <summary>
  29. /// Sets or returns a boolean indicating whether or not this instance has been disposed.
  30. /// </summary>
  31. /// <seealso cref="Dispose()"/>
  32. public bool IsDisposed
  33. {
  34. get;
  35. private set;
  36. }
  37. #endregion
  38. #region IDisposable Members
  39. /// <summary>
  40. /// Disposes this object instance and all internally managed resources.
  41. /// </summary>
  42. /// <remarks>
  43. /// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behaviour of derived classes.</para>
  44. /// </remarks>
  45. /// <seealso cref="IsDisposed"/>
  46. public void Dispose()
  47. {
  48. IsDisposed = true;
  49. Dispose(true);
  50. }
  51. #endregion
  52. }
  53. }