ToAsyncEnumerable.cs 11 KB

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