AsyncEnumerable.cs 2.6 KB

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