ToAsyncEnumerable.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace System.Linq
  12. {
  13. public static partial class AsyncEnumerable
  14. {
  15. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this IEnumerable<TSource> source)
  16. {
  17. if (source == null)
  18. throw new ArgumentNullException(nameof(source));
  19. // optimize these adapters for lists and collections
  20. var ilist = source as IList<TSource>;
  21. if (ilist != null)
  22. return new AsyncIListEnumerableAdapter<TSource>(ilist);
  23. var icoll = source as ICollection<TSource>;
  24. if (icoll != null)
  25. return new AsyncICollectionEnumerableAdapter<TSource>(icoll);
  26. return new AsyncEnumerableAdapter<TSource>(source);
  27. }
  28. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this Task<TSource> task)
  29. {
  30. if (task == null)
  31. throw new ArgumentNullException(nameof(task));
  32. return CreateEnumerable(
  33. () =>
  34. {
  35. var called = 0;
  36. var value = default(TSource);
  37. return CreateEnumerator(
  38. async ct =>
  39. {
  40. if (Interlocked.CompareExchange(ref called, 1, 0) == 0)
  41. {
  42. value = await task.ConfigureAwait(false);
  43. return true;
  44. }
  45. return false;
  46. },
  47. () => value,
  48. () => { });
  49. });
  50. }
  51. public static IEnumerable<TSource> ToEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
  52. {
  53. if (source == null)
  54. throw new ArgumentNullException(nameof(source));
  55. return ToEnumerable_(source);
  56. }
  57. private static IEnumerable<TSource> ToEnumerable_<TSource>(IAsyncEnumerable<TSource> source)
  58. {
  59. using (var e = source.GetEnumerator())
  60. {
  61. while (true)
  62. {
  63. if (!e.MoveNext(CancellationToken.None)
  64. .Result)
  65. break;
  66. var c = e.Current;
  67. yield return c;
  68. }
  69. }
  70. }
  71. internal sealed class AsyncEnumerableAdapter<T> : AsyncIterator<T>, IIListProvider<T>
  72. {
  73. private readonly IEnumerable<T> source;
  74. private IEnumerator<T> enumerator;
  75. public AsyncEnumerableAdapter(IEnumerable<T> source)
  76. {
  77. Debug.Assert(source != null);
  78. this.source = source;
  79. }
  80. public override AsyncIterator<T> Clone()
  81. {
  82. return new AsyncEnumerableAdapter<T>(source);
  83. }
  84. public override void Dispose()
  85. {
  86. if (enumerator != null)
  87. {
  88. enumerator.Dispose();
  89. enumerator = null;
  90. }
  91. base.Dispose();
  92. }
  93. protected override Task<bool> MoveNextCore(CancellationToken cancellationToken)
  94. {
  95. switch (state)
  96. {
  97. case AsyncIteratorState.Allocated:
  98. enumerator = source.GetEnumerator();
  99. state = AsyncIteratorState.Iterating;
  100. goto case AsyncIteratorState.Iterating;
  101. case AsyncIteratorState.Iterating:
  102. if (enumerator.MoveNext())
  103. {
  104. current = enumerator.Current;
  105. return Task.FromResult(true);
  106. }
  107. Dispose();
  108. break;
  109. }
  110. return Task.FromResult(false);
  111. }
  112. // These optimizations rely on the Sys.Linq impls from IEnumerable to optimize
  113. // and short circuit as appropriate
  114. public Task<T[]> ToArrayAsync(CancellationToken cancellationToken)
  115. {
  116. return Task.FromResult(source.ToArray());
  117. }
  118. public Task<List<T>> ToListAsync(CancellationToken cancellationToken)
  119. {
  120. return Task.FromResult(source.ToList());
  121. }
  122. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  123. {
  124. return Task.FromResult(source.Count());
  125. }
  126. }
  127. internal sealed class AsyncIListEnumerableAdapter<T> : AsyncIterator<T>, IIListProvider<T>, IList<T>
  128. {
  129. private readonly IList<T> source;
  130. private IEnumerator<T> enumerator;
  131. public AsyncIListEnumerableAdapter(IList<T> source)
  132. {
  133. Debug.Assert(source != null);
  134. this.source = source;
  135. }
  136. public override AsyncIterator<T> Clone()
  137. {
  138. return new AsyncEnumerableAdapter<T>(source);
  139. }
  140. public override void Dispose()
  141. {
  142. if (enumerator != null)
  143. {
  144. enumerator.Dispose();
  145. enumerator = null;
  146. }
  147. base.Dispose();
  148. }
  149. protected override Task<bool> MoveNextCore(CancellationToken cancellationToken)
  150. {
  151. switch (state)
  152. {
  153. case AsyncIteratorState.Allocated:
  154. enumerator = source.GetEnumerator();
  155. state = AsyncIteratorState.Iterating;
  156. goto case AsyncIteratorState.Iterating;
  157. case AsyncIteratorState.Iterating:
  158. if (enumerator.MoveNext())
  159. {
  160. current = enumerator.Current;
  161. return Task.FromResult(true);
  162. }
  163. Dispose();
  164. break;
  165. }
  166. return Task.FromResult(false);
  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 AsyncEnumerableAdapter<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. }