Retry.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 EnumerableEx
  8. {
  9. /// <summary>
  10. /// Creates a sequence that retries enumerating the source sequence as long as an error occurs.
  11. /// </summary>
  12. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  13. /// <param name="source">Source sequence.</param>
  14. /// <returns>Sequence concatenating the results of the source sequence as long as an error occurs.</returns>
  15. public static IEnumerable<TSource> Retry<TSource>(this IEnumerable<TSource> source)
  16. {
  17. if (source == null)
  18. throw new ArgumentNullException(nameof(source));
  19. return new[] { source }.Repeat().Catch();
  20. }
  21. /// <summary>
  22. /// Creates a sequence that retries enumerating the source sequence as long as an error occurs, with the specified
  23. /// maximum number of retries.
  24. /// </summary>
  25. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  26. /// <param name="source">Source sequence.</param>
  27. /// <param name="retryCount">Maximum number of retries.</param>
  28. /// <returns>Sequence concatenating the results of the source sequence as long as an error occurs.</returns>
  29. public static IEnumerable<TSource> Retry<TSource>(this IEnumerable<TSource> source, int retryCount)
  30. {
  31. if (source == null)
  32. throw new ArgumentNullException(nameof(source));
  33. if (retryCount < 0)
  34. throw new ArgumentOutOfRangeException(nameof(retryCount));
  35. return new[] { source }.Repeat(retryCount).Catch();
  36. }
  37. }
  38. }