RetryPolicyStateWithSleep<TResult>
using Polly.Utilities;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Polly.Retry
{
internal class RetryPolicyStateWithSleep<TResult> : IRetryPolicyState<TResult>
{
private readonly Func<DelegateResult<TResult>, TimeSpan, int, Context, Task> _onRetryAsync;
private int _errorCount;
private readonly Action<DelegateResult<TResult>, TimeSpan, int, Context> _onRetry;
private readonly Context _context;
private readonly IEnumerator<TimeSpan> _sleepDurationsEnumerator;
public RetryPolicyStateWithSleep(IEnumerable<TimeSpan> sleepDurations, Func<DelegateResult<TResult>, TimeSpan, int, Context, Task> onRetryAsync, Context context)
{
_onRetryAsync = onRetryAsync;
_context = context;
_sleepDurationsEnumerator = sleepDurations.GetEnumerator();
}
public RetryPolicyStateWithSleep(IEnumerable<TimeSpan> sleepDurations, Func<DelegateResult<TResult>, TimeSpan, Context, Task> onRetryAsync, Context context)
: this(sleepDurations, (Func<DelegateResult<TResult>, TimeSpan, int, Context, Task>)((DelegateResult<TResult> delegateResult, TimeSpan span, int i, Context c) => onRetryAsync(delegateResult, span, c)), context)
{
}
public async Task<bool> CanRetryAsync(DelegateResult<TResult> delegateResult, CancellationToken cancellationToken, bool continueOnCapturedContext)
{
if (!this._sleepDurationsEnumerator.MoveNext())
return false;
this._errorCount++;
TimeSpan currentTimeSpan = this._sleepDurationsEnumerator.Current;
await this._onRetryAsync(delegateResult, currentTimeSpan, this._errorCount, this._context).ConfigureAwait(continueOnCapturedContext);
await SystemClock.SleepAsync(currentTimeSpan, cancellationToken).ConfigureAwait(continueOnCapturedContext);
return true;
}
public RetryPolicyStateWithSleep(IEnumerable<TimeSpan> sleepDurations, Action<DelegateResult<TResult>, TimeSpan, int, Context> onRetry, Context context)
{
_onRetry = onRetry;
_context = context;
_sleepDurationsEnumerator = sleepDurations.GetEnumerator();
}
public RetryPolicyStateWithSleep(IEnumerable<TimeSpan> sleepDurations, Action<DelegateResult<TResult>, TimeSpan, Context> onRetry, Context context)
: this(sleepDurations, (Action<DelegateResult<TResult>, TimeSpan, int, Context>)delegate(DelegateResult<TResult> delegateResult, TimeSpan span, int i, Context c) {
onRetry(delegateResult, span, c);
}, context)
{
}
public bool CanRetry(DelegateResult<TResult> delegateResult, CancellationToken cancellationToken)
{
if (!_sleepDurationsEnumerator.MoveNext())
return false;
_errorCount++;
TimeSpan current = _sleepDurationsEnumerator.Current;
_onRetry(delegateResult, current, _errorCount, _context);
SystemClock.Sleep(current, cancellationToken);
return true;
}
}
}