Retry.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 AsyncEnumerable
  8. {
  9. public static IAsyncEnumerable<TSource> Retry<TSource>(this IAsyncEnumerable<TSource> source)
  10. {
  11. if (source == null)
  12. {
  13. throw new ArgumentNullException(nameof(source));
  14. }
  15. return new[] { source }.Repeat()
  16. .Catch();
  17. }
  18. public static IAsyncEnumerable<TSource> Retry<TSource>(this IAsyncEnumerable<TSource> source, int retryCount)
  19. {
  20. if (source == null)
  21. {
  22. throw new ArgumentNullException(nameof(source));
  23. }
  24. if (retryCount < 0)
  25. {
  26. throw new ArgumentOutOfRangeException(nameof(retryCount));
  27. }
  28. return new[] { source }.Repeat(retryCount)
  29. .Catch();
  30. }
  31. private static IEnumerable<TSource> Repeat<TSource>(this IEnumerable<TSource> source)
  32. {
  33. while (true)
  34. {
  35. foreach (var item in source)
  36. {
  37. yield return item;
  38. }
  39. }
  40. }
  41. private static IEnumerable<TSource> Repeat<TSource>(this IEnumerable<TSource> source, int count)
  42. {
  43. for (var i = 0; i < count; i++)
  44. {
  45. foreach (var item in source)
  46. {
  47. yield return item;
  48. }
  49. }
  50. }
  51. }
  52. }