Retry.cs 1.6 KB

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