Retry.cs 2.0 KB

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