RefCountDisposable.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Threading;
  5. namespace System.Reactive.Disposables
  6. {
  7. /// <summary>
  8. /// Represents a disposable resource that only disposes its underlying disposable resource when all <see cref="GetDisposable">dependent disposable objects</see> have been disposed.
  9. /// </summary>
  10. public sealed class RefCountDisposable : ICancelable
  11. {
  12. private readonly bool _throwWhenDisposed;
  13. private IDisposable _disposable;
  14. /// <summary>
  15. /// Holds the number of active child disposables and the
  16. /// indicator bit (31) if the main _disposable has been marked
  17. /// for disposition.
  18. /// </summary>
  19. private int _count;
  20. /// <summary>
  21. /// Initializes a new instance of the <see cref="RefCountDisposable"/> class with the specified disposable.
  22. /// </summary>
  23. /// <param name="disposable">Underlying disposable.</param>
  24. /// <exception cref="ArgumentNullException"><paramref name="disposable"/> is null.</exception>
  25. public RefCountDisposable(IDisposable disposable) : this(disposable, false)
  26. {
  27. }
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="RefCountDisposable"/> class with the specified disposable.
  30. /// </summary>
  31. /// <param name="disposable">Underlying disposable.</param>
  32. /// <param name="throwWhenDisposed">Indicates whether subsequent calls to <see cref="GetDisposable"/> should throw when this instance is disposed.</param>
  33. /// <exception cref="ArgumentNullException"><paramref name="disposable"/> is null.</exception>
  34. public RefCountDisposable(IDisposable disposable, bool throwWhenDisposed)
  35. {
  36. if (disposable == null)
  37. throw new ArgumentNullException(nameof(disposable));
  38. _disposable = disposable;
  39. _count = 0;
  40. _throwWhenDisposed = throwWhenDisposed;
  41. }
  42. /// <summary>
  43. /// Gets a value that indicates whether the object is disposed.
  44. /// </summary>
  45. public bool IsDisposed => Volatile.Read(ref _count) == int.MinValue;
  46. /// <summary>
  47. /// Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
  48. /// </summary>
  49. /// <returns>A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.</returns>
  50. /// <exception cref="ObjectDisposedException">This instance has been disposed and is configured to throw in this case by <see cref="RefCountDisposable(IDisposable, bool)"/>.</exception>
  51. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Backward compat + non-trivial work for a property getter.")]
  52. public IDisposable GetDisposable()
  53. {
  54. // the current state
  55. var cnt = Volatile.Read(ref _count);
  56. for (; ; )
  57. {
  58. // If bit 31 is set and the active count is zero, don't create an inner
  59. if (cnt == int.MinValue)
  60. {
  61. if (_throwWhenDisposed)
  62. throw new ObjectDisposedException("RefCountDisposable");
  63. return Disposable.Empty;
  64. }
  65. // Should not overflow the bits 0..30
  66. if ((cnt & 0x7FFFFFFF) == int.MaxValue)
  67. {
  68. throw new OverflowException($"RefCountDisposable can't handle more than {int.MaxValue} disposables");
  69. }
  70. // Increment the active count by one, works because the increment
  71. // won't affect bit 31
  72. var u = Interlocked.CompareExchange(ref _count, cnt + 1, cnt);
  73. if (u == cnt)
  74. {
  75. return new InnerDisposable(this);
  76. }
  77. cnt = u;
  78. }
  79. }
  80. /// <summary>
  81. /// Disposes the underlying disposable only when all dependent disposables have been disposed.
  82. /// </summary>
  83. public void Dispose()
  84. {
  85. var cnt = Volatile.Read(ref _count);
  86. for (; ; )
  87. {
  88. // already marked as disposed via bit 31?
  89. if ((cnt & 0x80000000) != 0)
  90. {
  91. // yes, nothing to do
  92. break;
  93. }
  94. // how many active disposables are there?
  95. var active = cnt & 0x7FFFFFFF;
  96. // keep the active count but set the dispose marker of bit 31
  97. var u = int.MinValue | active;
  98. var b = Interlocked.CompareExchange(ref _count, u, cnt);
  99. if (b == cnt) {
  100. // if there were 0 active disposables, there can't be any more after
  101. // the CAS so we can dispose the underlying disposable
  102. if (active == 0)
  103. {
  104. _disposable?.Dispose();
  105. _disposable = null;
  106. }
  107. break;
  108. }
  109. cnt = b;
  110. }
  111. }
  112. private void Release()
  113. {
  114. var cnt = Volatile.Read(ref _count);
  115. for (; ; )
  116. {
  117. // extract the main disposed state (bit 31)
  118. var main = (int)(cnt & 0x80000000);
  119. // get the active count
  120. var active = cnt & 0x7FFFFFFF;
  121. // keep the main disposed state but decrement the counter
  122. // in theory, active should be always > 0 at this point,
  123. // guaranteed by the InnerDisposable.Dispose's Exchange operation.
  124. System.Diagnostics.Debug.Assert(active > 0);
  125. var u = main | (active - 1);
  126. var b = Interlocked.CompareExchange(ref _count, u, cnt);
  127. if (b == cnt) {
  128. // if after the CAS there was zero active disposables and
  129. // the main has been also marked for disposing,
  130. // it is safe to dispose the underlying disposable
  131. if (u == int.MinValue)
  132. {
  133. _disposable?.Dispose();
  134. _disposable = null;
  135. }
  136. break;
  137. }
  138. cnt = b;
  139. }
  140. }
  141. private sealed class InnerDisposable : IDisposable
  142. {
  143. private RefCountDisposable _parent;
  144. public InnerDisposable(RefCountDisposable parent)
  145. {
  146. _parent = parent;
  147. }
  148. public void Dispose()
  149. {
  150. Interlocked.Exchange(ref _parent, null)?.Release();
  151. }
  152. }
  153. }
  154. }