1
0

Retry.cs 2.0 KB

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