ToAsyncEnumerable.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. () => TaskExt.True);
  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. var e = source.GetAsyncEnumerator();
  56. try
  57. {
  58. while (true)
  59. {
  60. if (!e.MoveNextAsync().Result)
  61. break;
  62. var c = e.Current;
  63. yield return c;
  64. }
  65. }
  66. finally
  67. {
  68. e.DisposeAsync().Wait();
  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 async Task DisposeAsync()
  85. {
  86. if (enumerator != null)
  87. {
  88. enumerator.Dispose();
  89. enumerator = null;
  90. }
  91. await base.DisposeAsync().ConfigureAwait(false);
  92. }
  93. protected override async Task<bool> MoveNextCore()
  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 true;
  106. }
  107. await DisposeAsync().ConfigureAwait(false);
  108. break;
  109. }
  110. return 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 AsyncIListEnumerableAdapter<T>(source);
  139. }
  140. public override async Task DisposeAsync()
  141. {
  142. if (enumerator != null)
  143. {
  144. enumerator.Dispose();
  145. enumerator = null;
  146. }
  147. await base.DisposeAsync().ConfigureAwait(false);
  148. }
  149. protected override async Task<bool> MoveNextCore()
  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 true;
  162. }
  163. await DisposeAsync().ConfigureAwait(false);
  164. break;
  165. }
  166. return false;
  167. }
  168. public override IAsyncEnumerable<TResult> Select<TResult>(Func<T, TResult> selector)
  169. {
  170. return new SelectIListIterator<T, TResult>(source, selector);
  171. }
  172. // These optimizations rely on the Sys.Linq impls from IEnumerable to optimize
  173. // and short circuit as appropriate
  174. public Task<T[]> ToArrayAsync(CancellationToken cancellationToken)
  175. {
  176. return Task.FromResult(source.ToArray());
  177. }
  178. public Task<List<T>> ToListAsync(CancellationToken cancellationToken)
  179. {
  180. return Task.FromResult(source.ToList());
  181. }
  182. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  183. {
  184. return Task.FromResult(source.Count);
  185. }
  186. IEnumerator<T> IEnumerable<T>.GetEnumerator() => source.GetEnumerator();
  187. IEnumerator IEnumerable.GetEnumerator() => source.GetEnumerator();
  188. void ICollection<T>.Add(T item) => source.Add(item);
  189. void ICollection<T>.Clear() => source.Clear();
  190. bool ICollection<T>.Contains(T item) => source.Contains(item);
  191. void ICollection<T>.CopyTo(T[] array, int arrayIndex) => source.CopyTo(array, arrayIndex);
  192. bool ICollection<T>.Remove(T item) => source.Remove(item);
  193. int ICollection<T>.Count => source.Count;
  194. bool ICollection<T>.IsReadOnly => source.IsReadOnly;
  195. int IList<T>.IndexOf(T item) => source.IndexOf(item);
  196. void IList<T>.Insert(int index, T item) => source.Insert(index, item);
  197. void IList<T>.RemoveAt(int index) => source.RemoveAt(index);
  198. T IList<T>.this[int index]
  199. {
  200. get { return source[index]; }
  201. set { source[index] = value; }
  202. }
  203. }
  204. internal sealed class AsyncICollectionEnumerableAdapter<T> : AsyncIterator<T>, IIListProvider<T>, ICollection<T>
  205. {
  206. private readonly ICollection<T> source;
  207. private IEnumerator<T> enumerator;
  208. public AsyncICollectionEnumerableAdapter(ICollection<T> source)
  209. {
  210. Debug.Assert(source != null);
  211. this.source = source;
  212. }
  213. public override AsyncIterator<T> Clone()
  214. {
  215. return new AsyncICollectionEnumerableAdapter<T>(source);
  216. }
  217. public override async Task DisposeAsync()
  218. {
  219. if (enumerator != null)
  220. {
  221. enumerator.Dispose();
  222. enumerator = null;
  223. }
  224. await base.DisposeAsync().ConfigureAwait(false);
  225. }
  226. protected override async Task<bool> MoveNextCore()
  227. {
  228. switch (state)
  229. {
  230. case AsyncIteratorState.Allocated:
  231. enumerator = source.GetEnumerator();
  232. state = AsyncIteratorState.Iterating;
  233. goto case AsyncIteratorState.Iterating;
  234. case AsyncIteratorState.Iterating:
  235. if (enumerator.MoveNext())
  236. {
  237. current = enumerator.Current;
  238. return true;
  239. }
  240. await DisposeAsync().ConfigureAwait(false);
  241. break;
  242. }
  243. return false;
  244. }
  245. // These optimizations rely on the Sys.Linq impls from IEnumerable to optimize
  246. // and short circuit as appropriate
  247. public Task<T[]> ToArrayAsync(CancellationToken cancellationToken)
  248. {
  249. return Task.FromResult(source.ToArray());
  250. }
  251. public Task<List<T>> ToListAsync(CancellationToken cancellationToken)
  252. {
  253. return Task.FromResult(source.ToList());
  254. }
  255. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  256. {
  257. return Task.FromResult(source.Count);
  258. }
  259. IEnumerator<T> IEnumerable<T>.GetEnumerator() => source.GetEnumerator();
  260. IEnumerator IEnumerable.GetEnumerator() => source.GetEnumerator();
  261. void ICollection<T>.Add(T item) => source.Add(item);
  262. void ICollection<T>.Clear() => source.Clear();
  263. bool ICollection<T>.Contains(T item) => source.Contains(item);
  264. void ICollection<T>.CopyTo(T[] array, int arrayIndex) => source.CopyTo(array, arrayIndex);
  265. bool ICollection<T>.Remove(T item) => source.Remove(item);
  266. int ICollection<T>.Count => source.Count;
  267. bool ICollection<T>.IsReadOnly => source.IsReadOnly;
  268. }
  269. }
  270. }