DisposableManagedObjectBase.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. namespace Emby.Common.Implementations.Net
  6. {
  7. /// <summary>
  8. /// 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.
  9. /// </summary>
  10. public abstract class DisposableManagedObjectBase : IDisposable
  11. {
  12. #region Public Methods
  13. /// <summary>
  14. /// Override this method and dispose any objects you own the lifetime of if disposing is true;
  15. /// </summary>
  16. /// <param name="disposing">True if managed objects should be disposed, if false, only unmanaged resources should be released.</param>
  17. protected abstract void Dispose(bool disposing);
  18. /// <summary>
  19. /// Throws and <see cref="System.ObjectDisposedException"/> if the <see cref="IsDisposed"/> property is true.
  20. /// </summary>
  21. /// <seealso cref="IsDisposed"/>
  22. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="IsDisposed"/> property is true.</exception>
  23. /// <seealso cref="Dispose()"/>
  24. protected virtual void ThrowIfDisposed()
  25. {
  26. if (this.IsDisposed) throw new ObjectDisposedException(this.GetType().FullName);
  27. }
  28. #endregion
  29. #region Public Properties
  30. /// <summary>
  31. /// Sets or returns a boolean indicating whether or not this instance has been disposed.
  32. /// </summary>
  33. /// <seealso cref="Dispose()"/>
  34. public bool IsDisposed
  35. {
  36. get;
  37. private set;
  38. }
  39. #endregion
  40. #region IDisposable Members
  41. /// <summary>
  42. /// Disposes this object instance and all internally managed resources.
  43. /// </summary>
  44. /// <remarks>
  45. /// <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>
  46. /// </remarks>
  47. /// <seealso cref="IsDisposed"/>
  48. public void Dispose()
  49. {
  50. try
  51. {
  52. IsDisposed = true;
  53. Dispose(true);
  54. }
  55. finally
  56. {
  57. GC.SuppressFinalize(this);
  58. }
  59. }
  60. #endregion
  61. }
  62. }