TailRecursiveSink.cs 8.0 KB

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