<PackageReference Include="Polly" Version="4.5.0-beta-netstandar-0001" />

RetryPolicyStateWithSleepDurationProvider<TResult>

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