ToAsyncEnumerable.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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.Generic;
  6. using System.Linq;
  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. return CreateEnumerable(
  18. () =>
  19. {
  20. var e = source.GetEnumerator();
  21. return CreateEnumerator(
  22. ct => Task.Run(() =>
  23. {
  24. var res = false;
  25. try
  26. {
  27. res = e.MoveNext();
  28. }
  29. finally
  30. {
  31. if (!res)
  32. e.Dispose();
  33. }
  34. return res;
  35. }, ct),
  36. () => e.Current,
  37. () => e.Dispose()
  38. );
  39. });
  40. }
  41. public static IAsyncEnumerable<TSource> ToAsyncEnumerable<TSource>(this Task<TSource> task)
  42. {
  43. if (task == null)
  44. throw new ArgumentNullException(nameof(task));
  45. return CreateEnumerable(
  46. () =>
  47. {
  48. var called = 0;
  49. var value = default(TSource);
  50. return CreateEnumerator(
  51. async ct =>
  52. {
  53. if (Interlocked.CompareExchange(ref called, 1, 0) == 0)
  54. {
  55. value = await task.ConfigureAwait(false);
  56. return true;
  57. }
  58. return false;
  59. },
  60. () => value,
  61. () => { });
  62. });
  63. }
  64. public static IEnumerable<TSource> ToEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
  65. {
  66. if (source == null)
  67. throw new ArgumentNullException(nameof(source));
  68. return ToEnumerable_(source);
  69. }
  70. private static IEnumerable<TSource> ToEnumerable_<TSource>(IAsyncEnumerable<TSource> source)
  71. {
  72. using (var e = source.GetEnumerator())
  73. {
  74. while (true)
  75. {
  76. if (!e.MoveNext(CancellationToken.None)
  77. .Result)
  78. break;
  79. var c = e.Current;
  80. yield return c;
  81. }
  82. }
  83. }
  84. }
  85. }