RetryPolicyStateWithSleepDurationProvider
using Polly.Utilities;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Polly.Retry
{
internal class RetryPolicyStateWithSleepDurationProvider : IRetryPolicyState
{
private int _errorCount;
private readonly Func<int, TimeSpan> _sleepDurationProvider;
private readonly Action<Exception, TimeSpan, Context> _onRetry;
private readonly Context _context;
private readonly Func<Exception, TimeSpan, Context, Task> _onRetryAsync;
public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan, Context> onRetry, Context context)
{
_sleepDurationProvider = sleepDurationProvider;
_onRetry = onRetry;
_context = context;
}
public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan> onRetry)
: this(sleepDurationProvider, delegate(Exception exception, TimeSpan timespan, Context context) {
onRetry(exception, timespan);
}, Context.Empty)
{
}
public bool CanRetry(Exception ex)
{
if (_errorCount < 2147483647)
_errorCount++;
TimeSpan timeSpan = _sleepDurationProvider(_errorCount);
_onRetry(ex, timeSpan, _context);
SystemClock.Sleep(timeSpan);
return true;
}
public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Func<Exception, TimeSpan, Context, Task> onRetryAsync, Context context)
{
_sleepDurationProvider = sleepDurationProvider;
_onRetryAsync = onRetryAsync;
_context = context;
}
public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Func<Exception, TimeSpan, Task> onRetryAsync)
: this(sleepDurationProvider, (Exception exception, TimeSpan timespan, Context context) => onRetryAsync(exception, timespan), Context.Empty)
{
}
public async Task<bool> CanRetryAsync(Exception ex, CancellationToken cancellationToken, bool continueOnCapturedContext)
{
if (_errorCount < 2147483647)
_errorCount++;
TimeSpan currentTimeSpan = _sleepDurationProvider(_errorCount);
await _onRetryAsync(ex, currentTimeSpan, _context).ConfigureAwait(continueOnCapturedContext);
await SystemClock.SleepAsync(currentTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext);
return true;
}
}
}