AsyncEnumerable.Conversions.cs 9.7 KB

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