<PackageReference Include="Polly" Version="4.2.3" />

RetryPolicyStateWithCount

using System; using System.Threading; using System.Threading.Tasks; namespace Polly.Retry { internal class RetryPolicyStateWithCount : IRetryPolicyState { private readonly Func<Exception, int, Context, Task> _onRetryAsync; private int _errorCount; private readonly int _retryCount; private readonly Action<Exception, int, Context> _onRetry; private readonly Context _context; public RetryPolicyStateWithCount(int retryCount, Func<Exception, int, Context, Task> onRetryAsync, Context context) { _retryCount = retryCount; _onRetryAsync = onRetryAsync; _context = context; } public RetryPolicyStateWithCount(int retryCount, Func<Exception, int, Task> onRetryAsync) : this(retryCount, (Exception exception, int i, Context context) => onRetryAsync(exception, i), Context.Empty) { } public async Task<bool> CanRetryAsync(Exception ex, CancellationToken ct, bool continueOnCapturedContext) { _errorCount++; bool shouldRetry = _errorCount <= _retryCount; if (shouldRetry) await _onRetryAsync(ex, _errorCount, _context).ConfigureAwait(continueOnCapturedContext); return shouldRetry; } public RetryPolicyStateWithCount(int retryCount, Action<Exception, int, Context> onRetry, Context context) { _retryCount = retryCount; _onRetry = onRetry; _context = context; } public RetryPolicyStateWithCount(int retryCount, Action<Exception, int> onRetry) : this(retryCount, delegate(Exception exception, int i, Context context) { onRetry(exception, i); }, Context.Empty) { } public bool CanRetry(Exception ex) { _errorCount++; bool num = _errorCount <= _retryCount; if (num) _onRetry(ex, _errorCount, _context); return num; } } }