AsyncEnumerable.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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> AsAsyncEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. return source.Select(x => x);
  18. }
  19. public static IAsyncEnumerable<TValue> Empty<TValue>()
  20. {
  21. return CreateEnumerable(
  22. () => CreateEnumerator<TValue>(
  23. ct => TaskExt.False,
  24. () => { throw new InvalidOperationException(); },
  25. () => { })
  26. );
  27. }
  28. public static Task<bool> IsEmpty<TSource>(this IAsyncEnumerable<TSource> source)
  29. {
  30. if (source == null)
  31. throw new ArgumentNullException(nameof(source));
  32. return source.IsEmpty(CancellationToken.None);
  33. }
  34. public static Task<bool> IsEmpty<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  35. {
  36. if (source == null)
  37. throw new ArgumentNullException(nameof(source));
  38. return IsEmpty_(source, cancellationToken);
  39. }
  40. public static IAsyncEnumerable<TValue> Never<TValue>()
  41. {
  42. return CreateEnumerable(
  43. () => CreateEnumerator<TValue>(
  44. (ct, tcs) => tcs.Task,
  45. () => { throw new InvalidOperationException(); },
  46. () => { })
  47. );
  48. }
  49. public static IAsyncEnumerable<TValue> Return<TValue>(TValue value)
  50. {
  51. return new[] {value}.ToAsyncEnumerable();
  52. }
  53. public static IAsyncEnumerable<TValue> Throw<TValue>(Exception exception)
  54. {
  55. if (exception == null)
  56. throw new ArgumentNullException(nameof(exception));
  57. return CreateEnumerable(
  58. () => CreateEnumerator<TValue>(
  59. ct => TaskExt.Throw<bool>(exception),
  60. () => { throw new InvalidOperationException(); },
  61. () => { })
  62. );
  63. }
  64. private static async Task<bool> IsEmpty_<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  65. {
  66. return !await source.Any(cancellationToken)
  67. .ConfigureAwait(false);
  68. }
  69. }
  70. }