ToAsyncEnumerable.cs 11 KB

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