AsyncEnumerable.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, null, null)
  24. );
  25. }
  26. public static Task<bool> IsEmpty<TSource>(this IAsyncEnumerable<TSource> source)
  27. {
  28. if (source == null)
  29. throw new ArgumentNullException(nameof(source));
  30. return source.IsEmpty(CancellationToken.None);
  31. }
  32. public static Task<bool> IsEmpty<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  33. {
  34. if (source == null)
  35. throw new ArgumentNullException(nameof(source));
  36. return IsEmpty_(source, cancellationToken);
  37. }
  38. public static IAsyncEnumerable<TValue> Never<TValue>()
  39. {
  40. return CreateEnumerable(
  41. () => CreateEnumerator<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 CreateEnumerable(
  56. () => CreateEnumerator<TValue>(
  57. ct => TaskExt.Throw<bool>(exception),
  58. () => { throw new InvalidOperationException(); },
  59. () => { })
  60. );
  61. }
  62. private static async Task<bool> IsEmpty_<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  63. {
  64. return !await source.Any(cancellationToken)
  65. .ConfigureAwait(false);
  66. }
  67. }
  68. }