Retry.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class AsyncEnumerableEx
  8. {
  9. /// <summary>
  10. /// Repeats the source async-enumerable sequence until it successfully terminates.
  11. /// </summary>
  12. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  13. /// <param name="source">Observable sequence to repeat until it successfully terminates.</param>
  14. /// <returns>An async-enumerable sequence producing the elements of the given sequence repeatedly until it terminates successfully.</returns>
  15. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  16. public static IAsyncEnumerable<TSource> Retry<TSource>(this IAsyncEnumerable<TSource> source)
  17. {
  18. if (source == null)
  19. throw Error.ArgumentNull(nameof(source));
  20. return new[] { source }.Repeat().Catch();
  21. }
  22. /// <summary>
  23. /// Repeats the source async-enumerable sequence the specified number of times or until it successfully terminates.
  24. /// </summary>
  25. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  26. /// <param name="source">Observable sequence to repeat until it successfully terminates.</param>
  27. /// <param name="retryCount">Number of times to repeat the sequence.</param>
  28. /// <returns>An async-enumerable sequence producing the elements of the given sequence repeatedly until it terminates successfully.</returns>
  29. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  30. /// <exception cref="ArgumentOutOfRangeException"><paramref name="retryCount"/> is less than zero.</exception>
  31. public static IAsyncEnumerable<TSource> Retry<TSource>(this IAsyncEnumerable<TSource> source, int retryCount)
  32. {
  33. if (source == null)
  34. throw Error.ArgumentNull(nameof(source));
  35. if (retryCount < 0)
  36. throw Error.ArgumentOutOfRange(nameof(retryCount));
  37. return new[] { source }.Repeat(retryCount).Catch();
  38. }
  39. private static IEnumerable<TSource> Repeat<TSource>(this IEnumerable<TSource> source)
  40. {
  41. while (true)
  42. {
  43. foreach (var item in source)
  44. {
  45. yield return item;
  46. }
  47. }
  48. }
  49. private static IEnumerable<TSource> Repeat<TSource>(this IEnumerable<TSource> source, int count)
  50. {
  51. for (var i = 0; i < count; i++)
  52. {
  53. foreach (var item in source)
  54. {
  55. yield return item;
  56. }
  57. }
  58. }
  59. }
  60. }