ToAsyncEnumerable.cs 2.8 KB

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