Retry.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. 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. foreach (var item in source)
  27. yield return item;
  28. }
  29. private static IEnumerable<TSource> Repeat<TSource>(this IEnumerable<TSource> source, int count)
  30. {
  31. for (var i = 0; i < count; i++)
  32. foreach (var item in source)
  33. yield return item;
  34. }
  35. }
  36. }