ToAsyncEnumerable.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  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. // optimize these adapters for lists and collections
  18. var list = source as IList<TSource>;
  19. if (list != null)
  20. return new AsyncIListEnumerableAdapter<TSource>(list);
  21. var collection = source as ICollection<TSource>;
  22. if (collection != null)
  23. return new AsyncICollectionEnumerableAdapter<TSource>(collection);
  24. return new AsyncEnumerableAdapter<TSource>(source);
  25. }
  26. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this Task<TSource> task)
  27. {
  28. if (task == null)
  29. throw new ArgumentNullException(nameof(task));
  30. return CreateEnumerable(
  31. () =>
  32. {
  33. var called = 0;
  34. var value = default(TSource);
  35. return CreateEnumerator(
  36. async ct =>
  37. {
  38. if (Interlocked.CompareExchange(ref called, 1, 0) == 0)
  39. {
  40. value = await task.ConfigureAwait(false);
  41. return true;
  42. }
  43. return false;
  44. },
  45. () => value,
  46. () => { });
  47. });
  48. }
  49. public static IEnumerable<TSource> ToEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
  50. {
  51. if (source == null)
  52. throw new ArgumentNullException(nameof(source));
  53. return ToEnumerable_(source);
  54. }
  55. private static IEnumerable<TSource> ToEnumerable_<TSource>(IAsyncEnumerable<TSource> source)
  56. {
  57. using (var e = source.GetEnumerator())
  58. {
  59. while (true)
  60. {
  61. if (!e.MoveNext(CancellationToken.None)
  62. .Result)
  63. break;
  64. var c = e.Current;
  65. yield return c;
  66. }
  67. }
  68. }
  69. internal sealed class AsyncEnumerableAdapter<T> : AsyncIterator<T>, IIListProvider<T>
  70. {
  71. private readonly IEnumerable<T> source;
  72. private IEnumerator<T> enumerator;
  73. public AsyncEnumerableAdapter(IEnumerable<T> source)
  74. {
  75. Debug.Assert(source != null);
  76. this.source = source;
  77. }
  78. public override AsyncIterator<T> Clone()
  79. {
  80. return new AsyncEnumerableAdapter<T>(source);
  81. }
  82. public override void Dispose()
  83. {
  84. if (enumerator != null)
  85. {
  86. enumerator.Dispose();
  87. enumerator = null;
  88. }
  89. base.Dispose();
  90. }
  91. protected override Task<bool> MoveNextCore(CancellationToken cancellationToken)
  92. {
  93. switch (state)
  94. {
  95. case AsyncIteratorState.Allocated:
  96. enumerator = source.GetEnumerator();
  97. state = AsyncIteratorState.Iterating;
  98. goto case AsyncIteratorState.Iterating;
  99. case AsyncIteratorState.Iterating:
  100. if (enumerator.MoveNext())
  101. {
  102. current = enumerator.Current;
  103. return Task.FromResult(true);
  104. }
  105. Dispose();
  106. break;
  107. }
  108. return Task.FromResult(false);
  109. }
  110. // These optimizations rely on the Sys.Linq impls from IEnumerable to optimize
  111. // and short circuit as appropriate
  112. public Task<T[]> ToArrayAsync(CancellationToken cancellationToken)
  113. {
  114. return Task.FromResult(source.ToArray());
  115. }
  116. public Task<List<T>> ToListAsync(CancellationToken cancellationToken)
  117. {
  118. return Task.FromResult(source.ToList());
  119. }
  120. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  121. {
  122. return Task.FromResult(source.Count());
  123. }
  124. }
  125. internal sealed class AsyncIListEnumerableAdapter<T> : AsyncIterator<T>, IIListProvider<T>, IList<T>
  126. {
  127. private readonly IList<T> source;
  128. private IEnumerator<T> enumerator;
  129. public AsyncIListEnumerableAdapter(IList<T> source)
  130. {
  131. Debug.Assert(source != null);
  132. this.source = source;
  133. }
  134. public override AsyncIterator<T> Clone()
  135. {
  136. return new AsyncIListEnumerableAdapter<T>(source);
  137. }
  138. public override void Dispose()
  139. {
  140. if (enumerator != null)
  141. {
  142. enumerator.Dispose();
  143. enumerator = null;
  144. }
  145. base.Dispose();
  146. }
  147. protected override Task<bool> MoveNextCore(CancellationToken cancellationToken)
  148. {
  149. switch (state)
  150. {
  151. case AsyncIteratorState.Allocated:
  152. enumerator = source.GetEnumerator();
  153. state = AsyncIteratorState.Iterating;
  154. goto case AsyncIteratorState.Iterating;
  155. case AsyncIteratorState.Iterating:
  156. if (enumerator.MoveNext())
  157. {
  158. current = enumerator.Current;
  159. return Task.FromResult(true);
  160. }
  161. Dispose();
  162. break;
  163. }
  164. return Task.FromResult(false);
  165. }
  166. public override IAsyncEnumerable<TResult> Select<TResult>(Func<T, TResult> selector)
  167. {
  168. return new SelectIListIterator<T, TResult>(source, selector);
  169. }
  170. // These optimizations rely on the Sys.Linq impls from IEnumerable to optimize
  171. // and short circuit as appropriate
  172. public Task<T[]> ToArrayAsync(CancellationToken cancellationToken)
  173. {
  174. return Task.FromResult(source.ToArray());
  175. }
  176. public Task<List<T>> ToListAsync(CancellationToken cancellationToken)
  177. {
  178. return Task.FromResult(source.ToList());
  179. }
  180. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  181. {
  182. return Task.FromResult(source.Count);
  183. }
  184. IEnumerator<T> IEnumerable<T>.GetEnumerator() => source.GetEnumerator();
  185. IEnumerator IEnumerable.GetEnumerator() => source.GetEnumerator();
  186. void ICollection<T>.Add(T item) => source.Add(item);
  187. void ICollection<T>.Clear() => source.Clear();
  188. bool ICollection<T>.Contains(T item) => source.Contains(item);
  189. void ICollection<T>.CopyTo(T[] array, int arrayIndex) => source.CopyTo(array, arrayIndex);
  190. bool ICollection<T>.Remove(T item) => source.Remove(item);
  191. int ICollection<T>.Count => source.Count;
  192. bool ICollection<T>.IsReadOnly => source.IsReadOnly;
  193. int IList<T>.IndexOf(T item) => source.IndexOf(item);
  194. void IList<T>.Insert(int index, T item) => source.Insert(index, item);
  195. void IList<T>.RemoveAt(int index) => source.RemoveAt(index);
  196. T IList<T>.this[int index]
  197. {
  198. get { return source[index]; }
  199. set { source[index] = value; }
  200. }
  201. }
  202. internal sealed class AsyncICollectionEnumerableAdapter<T> : AsyncIterator<T>, IIListProvider<T>, ICollection<T>
  203. {
  204. private readonly ICollection<T> source;
  205. private IEnumerator<T> enumerator;
  206. public AsyncICollectionEnumerableAdapter(ICollection<T> source)
  207. {
  208. Debug.Assert(source != null);
  209. this.source = source;
  210. }
  211. public override AsyncIterator<T> Clone()
  212. {
  213. return new AsyncICollectionEnumerableAdapter<T>(source);
  214. }
  215. public override void Dispose()
  216. {
  217. if (enumerator != null)
  218. {
  219. enumerator.Dispose();
  220. enumerator = null;
  221. }
  222. base.Dispose();
  223. }
  224. protected override Task<bool> MoveNextCore(CancellationToken cancellationToken)
  225. {
  226. switch (state)
  227. {
  228. case AsyncIteratorState.Allocated:
  229. enumerator = source.GetEnumerator();
  230. state = AsyncIteratorState.Iterating;
  231. goto case AsyncIteratorState.Iterating;
  232. case AsyncIteratorState.Iterating:
  233. if (enumerator.MoveNext())
  234. {
  235. current = enumerator.Current;
  236. return Task.FromResult(true);
  237. }
  238. Dispose();
  239. break;
  240. }
  241. return Task.FromResult(false);
  242. }
  243. // These optimizations rely on the Sys.Linq impls from IEnumerable to optimize
  244. // and short circuit as appropriate
  245. public Task<T[]> ToArrayAsync(CancellationToken cancellationToken)
  246. {
  247. return Task.FromResult(source.ToArray());
  248. }
  249. public Task<List<T>> ToListAsync(CancellationToken cancellationToken)
  250. {
  251. return Task.FromResult(source.ToList());
  252. }
  253. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  254. {
  255. return Task.FromResult(source.Count);
  256. }
  257. IEnumerator<T> IEnumerable<T>.GetEnumerator() => source.GetEnumerator();
  258. IEnumerator IEnumerable.GetEnumerator() => source.GetEnumerator();
  259. void ICollection<T>.Add(T item) => source.Add(item);
  260. void ICollection<T>.Clear() => source.Clear();
  261. bool ICollection<T>.Contains(T item) => source.Contains(item);
  262. void ICollection<T>.CopyTo(T[] array, int arrayIndex) => source.CopyTo(array, arrayIndex);
  263. bool ICollection<T>.Remove(T item) => source.Remove(item);
  264. int ICollection<T>.Count => source.Count;
  265. bool ICollection<T>.IsReadOnly => source.IsReadOnly;
  266. }
  267. }
  268. }