AsyncEnumerable.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. public static IAsyncEnumerable<TSource> AsAsyncEnumerable<TSource>(this IAsyncEnumerable<TSource> source)
  12. {
  13. if (source == null)
  14. {
  15. throw new ArgumentNullException(nameof(source));
  16. }
  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. {
  30. throw new ArgumentNullException(nameof(source));
  31. }
  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. {
  38. throw new ArgumentNullException(nameof(source));
  39. }
  40. return IsEmpty_(source, cancellationToken);
  41. }
  42. public static IAsyncEnumerable<TValue> Never<TValue>()
  43. {
  44. return CreateEnumerable(
  45. () => CreateEnumerator<TValue>(
  46. (ct, tcs) => tcs.Task,
  47. null,
  48. null)
  49. );
  50. }
  51. public static IAsyncEnumerable<TValue> Return<TValue>(TValue value)
  52. {
  53. return new[] { value }.ToAsyncEnumerable();
  54. }
  55. public static IAsyncEnumerable<TValue> Throw<TValue>(Exception exception)
  56. {
  57. if (exception == null)
  58. {
  59. throw new ArgumentNullException(nameof(exception));
  60. }
  61. return CreateEnumerable(
  62. () => CreateEnumerator<TValue>(
  63. ct =>
  64. {
  65. var tcs = new TaskCompletionSource<bool>();
  66. tcs.TrySetException(exception);
  67. return tcs.Task;
  68. },
  69. null,
  70. null)
  71. );
  72. }
  73. private static async Task<bool> IsEmpty_<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  74. {
  75. return !await source.Any(cancellationToken)
  76. .ConfigureAwait(false);
  77. }
  78. }
  79. }