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