DisposableManagedObjectBase.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. namespace Rssdp.Infrastructure
  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. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification="We do exactly as asked, but CA doesn't seem to like us also setting the IsDisposed property. Too bad, it's a good idea and shouldn't cause an exception or anything likely to interfer with the dispose process.")]
  49. public void Dispose()
  50. {
  51. try
  52. {
  53. IsDisposed = true;
  54. Dispose(true);
  55. }
  56. finally
  57. {
  58. GC.SuppressFinalize(this);
  59. }
  60. }
  61. #endregion
  62. }
  63. }