Repeat.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 AsyncEnumerableEx
  10. {
  11. public static IAsyncEnumerable<TResult> Repeat<TResult>(TResult element)
  12. {
  13. return AsyncEnumerable.Create(Core);
  14. #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
  15. async IAsyncEnumerator<TResult> Core(CancellationToken cancellationToken)
  16. {
  17. while (true)
  18. {
  19. cancellationToken.ThrowIfCancellationRequested();
  20. yield return element;
  21. }
  22. }
  23. #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
  24. }
  25. public static IAsyncEnumerable<TSource> Repeat<TSource>(this IAsyncEnumerable<TSource> source)
  26. {
  27. if (source == null)
  28. throw Error.ArgumentNull(nameof(source));
  29. return AsyncEnumerable.Create(Core);
  30. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  31. {
  32. while (true)
  33. {
  34. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  35. {
  36. yield return item;
  37. }
  38. }
  39. }
  40. }
  41. public static IAsyncEnumerable<TSource> Repeat<TSource>(this IAsyncEnumerable<TSource> source, int count)
  42. {
  43. if (source == null)
  44. throw Error.ArgumentNull(nameof(source));
  45. if (count < 0)
  46. throw Error.ArgumentOutOfRange(nameof(count));
  47. return AsyncEnumerable.Create(Core);
  48. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  49. {
  50. for (var i = 0; i < count; i++)
  51. {
  52. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  53. {
  54. yield return item;
  55. }
  56. }
  57. }
  58. }
  59. }
  60. }