AsyncEnumerable.Conversions.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using System.Threading;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this IEnumerable<TSource> source)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. return Create(() =>
  18. {
  19. var e = source.GetEnumerator();
  20. return Create(
  21. ct => Task.Factory.StartNew(() =>
  22. {
  23. var res = default(bool);
  24. try
  25. {
  26. res = e.MoveNext();
  27. }
  28. finally
  29. {
  30. if (!res)
  31. e.Dispose();
  32. }
  33. return res;
  34. }, ct),
  35. () => e.Current,
  36. () => e.Dispose()
  37. );
  38. });
  39. }
  40. public static IEnumerable<TSource> ToEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
  41. {
  42. if (source == null)
  43. throw new ArgumentNullException(nameof(source));
  44. return ToEnumerable_(source);
  45. }
  46. private static IEnumerable<TSource> ToEnumerable_<TSource>(IAsyncEnumerable<TSource> source)
  47. {
  48. using (var e = source.GetEnumerator())
  49. {
  50. while (true)
  51. {
  52. var t = e.MoveNext(CancellationToken.None);
  53. t.Wait();
  54. if (!t.Result)
  55. break;
  56. var c = e.Current;
  57. yield return c;
  58. }
  59. }
  60. }
  61. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this Task<TSource> task)
  62. {
  63. if (task == null)
  64. throw new ArgumentNullException(nameof(task));
  65. return Create(() =>
  66. {
  67. var called = 0;
  68. var value = default(TSource);
  69. return Create(
  70. async ct =>
  71. {
  72. if (Interlocked.CompareExchange(ref called, 1, 0) == 0)
  73. {
  74. value = await task.ConfigureAwait(false);
  75. return true;
  76. }
  77. return false;
  78. },
  79. () => value,
  80. () => { });
  81. });
  82. }
  83. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this IObservable<TSource> source)
  84. {
  85. if (source == null)
  86. throw new ArgumentNullException("source");
  87. return Create(() =>
  88. {
  89. var observer = new ToAsyncEnumerableObserver<TSource>();
  90. var subscription = source.Subscribe(observer);
  91. return Create(
  92. (ct, tcs) =>
  93. {
  94. var hasValue = false;
  95. var hasCompleted = false;
  96. var error = default(Exception);
  97. lock (observer.SyncRoot)
  98. {
  99. if (observer.Values.Count > 0)
  100. {
  101. hasValue = true;
  102. observer.Current = observer.Values.Dequeue();
  103. }
  104. else if (observer.HasCompleted)
  105. {
  106. hasCompleted = true;
  107. }
  108. else if (observer.Error != null)
  109. {
  110. error = observer.Error;
  111. }
  112. else
  113. {
  114. observer.TaskCompletionSource = tcs;
  115. }
  116. }
  117. if (hasValue)
  118. {
  119. tcs.TrySetResult(true);
  120. }
  121. else if (hasCompleted)
  122. {
  123. tcs.TrySetResult(false);
  124. }
  125. else if (error != null)
  126. {
  127. tcs.TrySetException(error);
  128. }
  129. return tcs.Task;
  130. },
  131. () => observer.Current,
  132. () =>
  133. {
  134. subscription.Dispose();
  135. // Should we cancel in-flight operations somehow?
  136. });
  137. });
  138. }
  139. class ToAsyncEnumerableObserver<T> : IObserver<T>
  140. {
  141. public ToAsyncEnumerableObserver()
  142. {
  143. Values = new Queue<T>();
  144. }
  145. public object SyncRoot
  146. {
  147. get { return Values; }
  148. }
  149. public readonly Queue<T> Values;
  150. public Exception Error;
  151. public bool HasCompleted;
  152. public T Current;
  153. public TaskCompletionSource<bool> TaskCompletionSource;
  154. public void OnCompleted()
  155. {
  156. var tcs = default(TaskCompletionSource<bool>);
  157. lock (SyncRoot)
  158. {
  159. HasCompleted = true;
  160. if (TaskCompletionSource != null)
  161. {
  162. tcs = TaskCompletionSource;
  163. TaskCompletionSource = null;
  164. }
  165. }
  166. if (tcs != null)
  167. {
  168. tcs.SetResult(false);
  169. }
  170. }
  171. public void OnError(Exception error)
  172. {
  173. var tcs = default(TaskCompletionSource<bool>);
  174. lock (SyncRoot)
  175. {
  176. Error = error;
  177. if (TaskCompletionSource != null)
  178. {
  179. tcs = TaskCompletionSource;
  180. TaskCompletionSource = null;
  181. }
  182. }
  183. if (tcs != null)
  184. {
  185. tcs.SetException(error);
  186. }
  187. }
  188. public void OnNext(T value)
  189. {
  190. var tcs = default(TaskCompletionSource<bool>);
  191. lock (SyncRoot)
  192. {
  193. if (TaskCompletionSource == null)
  194. {
  195. Values.Enqueue(value);
  196. }
  197. else
  198. {
  199. Current = value;
  200. tcs = TaskCompletionSource;
  201. TaskCompletionSource = null;
  202. }
  203. }
  204. if (tcs != null)
  205. {
  206. tcs.SetResult(true);
  207. }
  208. }
  209. }
  210. public static IObservable<TSource> ToObservable<TSource>(this IAsyncEnumerable<TSource> source)
  211. {
  212. if (source == null)
  213. throw new ArgumentNullException("source");
  214. return new ToObservableObservable<TSource>(source);
  215. }
  216. class ToObservableObservable<T> : IObservable<T>
  217. {
  218. private readonly IAsyncEnumerable<T> source;
  219. public ToObservableObservable(IAsyncEnumerable<T> source)
  220. {
  221. this.source = source;
  222. }
  223. public IDisposable Subscribe(IObserver<T> observer)
  224. {
  225. var ctd = new CancellationTokenDisposable();
  226. var e = source.GetEnumerator();
  227. var f = default(Action);
  228. f = () => e.MoveNext(ctd.Token).ContinueWith(t =>
  229. {
  230. if (t.IsFaulted)
  231. {
  232. observer.OnError(t.Exception);
  233. e.Dispose();
  234. }
  235. else if (t.IsCanceled)
  236. {
  237. e.Dispose();
  238. }
  239. else if (t.IsCompleted)
  240. {
  241. if (t.Result)
  242. {
  243. observer.OnNext(e.Current);
  244. f();
  245. }
  246. else
  247. {
  248. observer.OnCompleted();
  249. e.Dispose();
  250. }
  251. }
  252. }, ctd.Token);
  253. f();
  254. return Disposable.Create(ctd, e);
  255. }
  256. }
  257. }
  258. }