DisposableManagedObjectBase.cs 2.4 KB

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