ToAsyncEnumerable.cs 11 KB

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