AsyncEnumerable.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. null,
  44. null)
  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 =>
  58. {
  59. var tcs = new TaskCompletionSource<bool>();
  60. tcs.TrySetException(exception);
  61. return tcs.Task;
  62. },
  63. null,
  64. null)
  65. );
  66. }
  67. private static async Task<bool> IsEmpty_<TSource>(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  68. {
  69. return !await source.Any(cancellationToken)
  70. .ConfigureAwait(false);
  71. }
  72. }
  73. }