TailRecursiveSink.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Reactive.Disposables;
  7. using System.Threading;
  8. namespace System.Reactive
  9. {
  10. internal abstract class TailRecursiveSink<TSource> : IdentitySink<TSource>
  11. {
  12. private readonly Stack<IEnumerator<IObservable<TSource>>> _stack = new Stack<IEnumerator<IObservable<TSource>>>();
  13. private bool _isDisposed;
  14. private int _trampoline;
  15. private IDisposable? _currentSubscription;
  16. protected TailRecursiveSink(IObserver<TSource> observer)
  17. : base(observer)
  18. {
  19. }
  20. public void Run(IEnumerable<IObservable<TSource>> sources)
  21. {
  22. if (!TryGetEnumerator(sources, out var current))
  23. {
  24. return;
  25. }
  26. _stack.Push(current);
  27. Drain();
  28. }
  29. protected override void Dispose(bool disposing)
  30. {
  31. if (disposing)
  32. {
  33. DisposeAll();
  34. }
  35. base.Dispose(disposing);
  36. }
  37. private void Drain()
  38. {
  39. if (Interlocked.Increment(ref _trampoline) != 1)
  40. {
  41. return;
  42. }
  43. for (; ; )
  44. {
  45. if (Volatile.Read(ref _isDisposed))
  46. {
  47. while (_stack.Count != 0)
  48. {
  49. var enumerator = _stack.Pop();
  50. enumerator.Dispose();
  51. }
  52. Disposable.TryDispose(ref _currentSubscription);
  53. }
  54. else
  55. {
  56. if (_stack.Count != 0)
  57. {
  58. var currentEnumerator = _stack.Peek();
  59. var currentObservable = default(IObservable<TSource>);
  60. try
  61. {
  62. if (currentEnumerator.MoveNext())
  63. {
  64. currentObservable = currentEnumerator.Current;
  65. }
  66. }
  67. catch (Exception ex)
  68. {
  69. currentEnumerator.Dispose();
  70. ForwardOnError(ex);
  71. Volatile.Write(ref _isDisposed, true);
  72. continue;
  73. }
  74. IObservable<TSource>? next;
  75. try
  76. {
  77. next = Helpers.Unpack(currentObservable);
  78. }
  79. catch (Exception ex)
  80. {
  81. if (!Fail(ex))
  82. {
  83. Volatile.Write(ref _isDisposed, true);
  84. }
  85. continue;
  86. }
  87. if (next != null)
  88. {
  89. var nextSeq = Extract(next);
  90. if (nextSeq != null)
  91. {
  92. if (TryGetEnumerator(nextSeq, out var nextEnumerator))
  93. {
  94. _stack.Push(nextEnumerator);
  95. continue;
  96. }
  97. Volatile.Write(ref _isDisposed, true);
  98. continue;
  99. }
  100. // we need an unique indicator for this as
  101. // Subscribe could return a Disposable.Empty or
  102. // a BooleanDisposable
  103. var sad = ReadyToken.Ready;
  104. // Swap in the Ready indicator so we know the sequence hasn't been disposed
  105. if (Disposable.TrySetSingle(ref _currentSubscription, sad) == TrySetSingleResult.Success)
  106. {
  107. // subscribe to the source
  108. var d = next.SubscribeSafe(this);
  109. // Try to swap in the returned disposable in place of the Ready indicator
  110. // Since this drain loop is the only one to use Ready, this should
  111. // be unambiguous
  112. var u = Interlocked.CompareExchange(ref _currentSubscription, d, sad);
  113. // sequence disposed or completed synchronously
  114. if (u != sad)
  115. {
  116. d.Dispose();
  117. if (u == BooleanDisposable.True)
  118. {
  119. continue;
  120. }
  121. }
  122. }
  123. else
  124. {
  125. continue;
  126. }
  127. }
  128. else
  129. {
  130. _stack.Pop();
  131. currentEnumerator.Dispose();
  132. continue;
  133. }
  134. }
  135. else
  136. {
  137. Volatile.Write(ref _isDisposed, true);
  138. Done();
  139. }
  140. }
  141. if (Interlocked.Decrement(ref _trampoline) == 0)
  142. {
  143. break;
  144. }
  145. }
  146. }
  147. private void DisposeAll()
  148. {
  149. Volatile.Write(ref _isDisposed, true);
  150. // the disposing of currentSubscription is deferred to drain due to some ObservableExTest.Iterate_Complete()
  151. // Interlocked.Exchange(ref currentSubscription, BooleanDisposable.True)?.Dispose();
  152. Drain();
  153. }
  154. protected void Recurse()
  155. {
  156. if (Disposable.TrySetSerial(ref _currentSubscription, null))
  157. {
  158. Drain();
  159. }
  160. }
  161. protected abstract IEnumerable<IObservable<TSource>>? Extract(IObservable<TSource> source);
  162. private bool TryGetEnumerator(IEnumerable<IObservable<TSource>> sources, [NotNullWhen(true)] out IEnumerator<IObservable<TSource>>? result)
  163. {
  164. try
  165. {
  166. result = sources.GetEnumerator();
  167. return true;
  168. }
  169. catch (Exception exception)
  170. {
  171. ForwardOnError(exception);
  172. result = null;
  173. return false;
  174. }
  175. }
  176. protected virtual void Done()
  177. {
  178. ForwardOnCompleted();
  179. }
  180. protected virtual bool Fail(Exception error)
  181. {
  182. ForwardOnError(error);
  183. return false;
  184. }
  185. }
  186. /// <summary>
  187. /// Holds onto a singleton IDisposable indicating a ready state.
  188. /// </summary>
  189. internal static class ReadyToken
  190. {
  191. /// <summary>
  192. /// This indicates the operation has been prepared and ready for
  193. /// the next step.
  194. /// </summary>
  195. internal static readonly IDisposable Ready = new ReadyDisposable();
  196. private sealed class ReadyDisposable : IDisposable
  197. {
  198. public void Dispose()
  199. {
  200. // deliberately no-op
  201. }
  202. }
  203. }
  204. }