AsyncEnumerable.Creation.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. static IAsyncEnumerable<T> Create<T>(Func<IAsyncEnumerator<T>> getEnumerator)
  14. {
  15. return new AnonymousAsyncEnumerable<T>(getEnumerator);
  16. }
  17. class AnonymousAsyncEnumerable<T> : IAsyncEnumerable<T>
  18. {
  19. Func<IAsyncEnumerator<T>> getEnumerator;
  20. public AnonymousAsyncEnumerable(Func<IAsyncEnumerator<T>> getEnumerator)
  21. {
  22. this.getEnumerator = getEnumerator;
  23. }
  24. public IAsyncEnumerator<T> GetEnumerator()
  25. {
  26. return getEnumerator();
  27. }
  28. }
  29. static IAsyncEnumerator<T> Create<T>(Func<CancellationToken, Task<bool>> moveNext, Func<T> current, Action dispose)
  30. {
  31. return new AnonymousAsyncEnumerator<T>(moveNext, current, dispose);
  32. }
  33. static IAsyncEnumerator<T> Create<T>(Func<CancellationToken, TaskCompletionSource<bool>, Task<bool>> moveNext, Func<T> current, Action dispose)
  34. {
  35. var self = default(IAsyncEnumerator<T>);
  36. self = new AnonymousAsyncEnumerator<T>(
  37. ct =>
  38. {
  39. var tcs = new TaskCompletionSource<bool>();
  40. var stop = new Action(() =>
  41. {
  42. self.Dispose();
  43. tcs.TrySetCanceled();
  44. });
  45. var ctr = ct.Register(stop);
  46. var res = moveNext(ct, tcs).Finally(ctr.Dispose);
  47. return res;
  48. },
  49. current,
  50. dispose
  51. );
  52. return self;
  53. }
  54. class AnonymousAsyncEnumerator<T> : IAsyncEnumerator<T>
  55. {
  56. private readonly Func<CancellationToken, Task<bool>> _moveNext;
  57. private readonly Func<T> _current;
  58. private readonly Action _dispose;
  59. private bool _disposed;
  60. public AnonymousAsyncEnumerator(Func<CancellationToken, Task<bool>> moveNext, Func<T> current, Action dispose)
  61. {
  62. _moveNext = moveNext;
  63. _current = current;
  64. _dispose = dispose;
  65. }
  66. public Task<bool> MoveNext(CancellationToken cancellationToken)
  67. {
  68. if (_disposed)
  69. return TaskExt.False;
  70. return _moveNext(cancellationToken);
  71. }
  72. public T Current
  73. {
  74. get
  75. {
  76. return _current();
  77. }
  78. }
  79. public void Dispose()
  80. {
  81. if (!_disposed)
  82. {
  83. _disposed = true;
  84. _dispose();
  85. }
  86. }
  87. }
  88. public static IAsyncEnumerable<TValue> Return<TValue>(TValue value)
  89. {
  90. return new[] { value }.ToAsyncEnumerable();
  91. }
  92. public static IAsyncEnumerable<TValue> Throw<TValue>(Exception exception)
  93. {
  94. if (exception == null)
  95. throw new ArgumentNullException("exception");
  96. return Create(() => Create<TValue>(
  97. ct => TaskExt.Throw<bool>(exception),
  98. () => { throw new InvalidOperationException(); },
  99. () => { })
  100. );
  101. }
  102. public static IAsyncEnumerable<TValue> Never<TValue>()
  103. {
  104. return Create(() => Create<TValue>(
  105. (ct, tcs) => tcs.Task,
  106. () => { throw new InvalidOperationException(); },
  107. () => { })
  108. );
  109. }
  110. public static IAsyncEnumerable<TValue> Empty<TValue>()
  111. {
  112. return Create(() => Create<TValue>(
  113. ct => TaskExt.False,
  114. () => { throw new InvalidOperationException(); },
  115. () => { })
  116. );
  117. }
  118. public static IAsyncEnumerable<int> Range(int start, int count)
  119. {
  120. if (count < 0)
  121. throw new ArgumentOutOfRangeException("count");
  122. return Enumerable.Range(start, count).ToAsyncEnumerable();
  123. }
  124. public static IAsyncEnumerable<TResult> Repeat<TResult>(TResult element, int count)
  125. {
  126. if (count < 0)
  127. throw new ArgumentOutOfRangeException("count");
  128. return Enumerable.Repeat(element, count).ToAsyncEnumerable();
  129. }
  130. public static IAsyncEnumerable<TResult> Repeat<TResult>(TResult element)
  131. {
  132. return Create(() =>
  133. {
  134. return Create(
  135. ct => TaskExt.True,
  136. () => element,
  137. () => { }
  138. );
  139. });
  140. }
  141. public static IAsyncEnumerable<TSource> Defer<TSource>(Func<IAsyncEnumerable<TSource>> factory)
  142. {
  143. if (factory == null)
  144. throw new ArgumentNullException("factory");
  145. return Create(() => factory().GetEnumerator());
  146. }
  147. public static IAsyncEnumerable<TResult> Generate<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  148. {
  149. if (condition == null)
  150. throw new ArgumentNullException("condition");
  151. if (iterate == null)
  152. throw new ArgumentNullException("iterate");
  153. if (resultSelector == null)
  154. throw new ArgumentNullException("resultSelector");
  155. return Create(() =>
  156. {
  157. var i = initialState;
  158. var started = false;
  159. var current = default(TResult);
  160. return Create(
  161. ct =>
  162. {
  163. var b = false;
  164. try
  165. {
  166. if (started)
  167. i = iterate(i);
  168. b = condition(i);
  169. if (b)
  170. current = resultSelector(i);
  171. }
  172. catch (Exception ex)
  173. {
  174. return TaskExt.Throw<bool>(ex);
  175. }
  176. if (!b)
  177. return TaskExt.False;
  178. if (!started)
  179. started = true;
  180. return TaskExt.True;
  181. },
  182. () => current,
  183. () => { }
  184. );
  185. });
  186. }
  187. public static IAsyncEnumerable<TSource> Using<TSource, TResource>(Func<TResource> resourceFactory, Func<TResource, IAsyncEnumerable<TSource>> enumerableFactory) where TResource : IDisposable
  188. {
  189. if (resourceFactory == null)
  190. throw new ArgumentNullException("resourceFactory");
  191. if (enumerableFactory == null)
  192. throw new ArgumentNullException("enumerableFactory");
  193. return Create(() =>
  194. {
  195. var resource = resourceFactory();
  196. var e = default(IAsyncEnumerator<TSource>);
  197. try
  198. {
  199. e = enumerableFactory(resource).GetEnumerator();
  200. }
  201. catch (Exception)
  202. {
  203. resource.Dispose();
  204. throw;
  205. }
  206. var cts = new CancellationTokenDisposable();
  207. var d = Disposable.Create(cts, resource, e);
  208. var current = default(TSource);
  209. return Create(
  210. (ct, tcs) =>
  211. {
  212. e.MoveNext(cts.Token).Then(t =>
  213. {
  214. t.Handle(tcs,
  215. res =>
  216. {
  217. if (res)
  218. {
  219. current = e.Current;
  220. tcs.TrySetResult(true);
  221. }
  222. else
  223. {
  224. d.Dispose();
  225. tcs.TrySetResult(false);
  226. }
  227. },
  228. ex =>
  229. {
  230. d.Dispose();
  231. tcs.TrySetException(ex);
  232. }
  233. );
  234. });
  235. return tcs.Task;
  236. },
  237. () => current,
  238. d.Dispose
  239. );
  240. });
  241. }
  242. }
  243. }