AsyncEnumerable.cs 2.7 KB

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