RetryPolicy Class
- Namespace
- Kampute.Resilience
- Assembly
- Kampute.Resilience.dll
Definition
public sealed class RetryPolicy- Inheritance
- object
- RetryPolicy
Remarks
Examples
var retry = RetryStrategies.Exponential(TimeSpan.FromSeconds(1))
.WithMaxRetries(5)
.RetryOn<TimeoutException>()
.OnRetry(context => Console.WriteLine($"Attempt {context.AttemptNumber} failed; retrying in {context.Delay}."));
var value = await retry.ExecuteAsync(ct => LoadAsync(ct), cancellationToken);Constructors
RetryPolicy(IRetryStrategy)
public RetryPolicy(IRetryStrategy strategy)Parameters
strategyIRetryStrategy- The strategy that decides whether and when to retry.
Exceptions
- ArgumentNullException
- Thrown if
strategyisnull.
Properties
Strategy
public IRetryStrategy Strategy { get; }Property Value
- IRetryStrategy
- The IRetryStrategy that decides whether and when to retry.
Methods
Execute(Action<CancellationToken>, CancellationToken)
public void Execute(Action<CancellationToken> operation, CancellationToken cancellationToken = default)Parameters
operationAction<CancellationToken>- The operation to run. It receives
cancellationToken. cancellationTokenCancellationToken optional- A token for canceling the operation and the waits between attempts (optional).
Exceptions
- ArgumentNullException
- Thrown if
operationisnull. - OperationCanceledException
- Thrown if
cancellationTokenis canceled while waiting before a retry.
Remarks
Execute<T>(Func<CancellationToken, T>, CancellationToken)
public T Execute<T>(Func<CancellationToken, T> operation, CancellationToken cancellationToken = default)Type Parameters
T- The type of the value the operation returns.
Parameters
operationFunc<CancellationToken, T>- The operation to run. It receives
cancellationToken. cancellationTokenCancellationToken optional- A token for canceling the operation and the waits between attempts (optional).
Returns
- T
- The value returned by the first successful run of the operation.
Exceptions
- ArgumentNullException
- Thrown if
operationisnull. - OperationCanceledException
- Thrown if
cancellationTokenis canceled while waiting before a retry.
Remarks
Execute<TState>(TState, Action<TState, CancellationToken>, CancellationToken)
public void Execute<TState>(TState state, Action<TState, CancellationToken> operation, CancellationToken cancellationToken = default)Type Parameters
TState- The type of the state passed to the operation.
Parameters
stateTState- The state passed to every attempt of the operation.
operationAction<TState, CancellationToken>- The operation to run. It receives
stateandcancellationToken. cancellationTokenCancellationToken optional- A token for canceling the operation and the waits between attempts (optional).
Exceptions
- ArgumentNullException
- Thrown if
operationisnull. - OperationCanceledException
- Thrown if
cancellationTokenis canceled while waiting before a retry.
Remarks
The calling thread is blocked during the waits between attempts. When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.
Pass the values that the operation needs as state and use an operation that captures no variables, such as a static lambda; the compiler then reuses one delegate instance, so the call allocates no closure. Use a tuple to pass several values.
Execute<TState, T>(TState, Func<TState, CancellationToken, T>, CancellationToken)
public T Execute<TState, T>(TState state, Func<TState, CancellationToken, T> operation, CancellationToken cancellationToken = default)Type Parameters
TState- The type of the state passed to the operation.
T- The type of the value the operation returns.
Parameters
stateTState- The state passed to every attempt of the operation.
operationFunc<TState, CancellationToken, T>- The operation to run. It receives
stateandcancellationToken. cancellationTokenCancellationToken optional- A token for canceling the operation and the waits between attempts (optional).
Returns
- T
- The value returned by the first successful run of the operation.
Exceptions
- ArgumentNullException
- Thrown if
operationisnull. - OperationCanceledException
- Thrown if
cancellationTokenis canceled while waiting before a retry.
Remarks
The calling thread is blocked during the waits between attempts. When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.
Pass the values that the operation needs as state and use an operation that captures no variables, such as a static lambda; the compiler then reuses one delegate instance, so the call allocates no closure. Use a tuple to pass several values.
ExecuteAsync(Func<CancellationToken, Task>, CancellationToken)
public Task ExecuteAsync(Func<CancellationToken, Task> operation, CancellationToken cancellationToken = default)Parameters
operationFunc<CancellationToken, Task>- The operation to run. It receives
cancellationToken. cancellationTokenCancellationToken optional- A token for canceling the operation and the waits between attempts (optional).
Returns
- Task
- A task that completes when the operation succeeds.
Exceptions
- ArgumentNullException
- Thrown, before a task is returned, if
operationisnull. - OperationCanceledException
- Thrown if
cancellationTokenis canceled while waiting before a retry.
Remarks
ExecuteAsync<T>(Func<CancellationToken, Task<T>>, CancellationToken)
public Task<T> ExecuteAsync<T>(Func<CancellationToken, Task<T>> operation, CancellationToken cancellationToken = default)Type Parameters
T- The type of the value the operation returns.
Parameters
operationFunc<CancellationToken, Task<T>>- The operation to run. It receives
cancellationToken. cancellationTokenCancellationToken optional- A token for canceling the operation and the waits between attempts (optional).
Returns
- Task<T>
- A task that resolves to the value returned by the first successful run of the operation.
Exceptions
- ArgumentNullException
- Thrown, before a task is returned, if
operationisnull. - OperationCanceledException
- Thrown if
cancellationTokenis canceled while waiting before a retry.
Remarks
ExecuteAsync<TState>(TState, Func<TState, CancellationToken, Task>, CancellationToken)
public Task ExecuteAsync<TState>(TState state, Func<TState, CancellationToken, Task> operation, CancellationToken cancellationToken = default)Type Parameters
TState- The type of the state passed to the operation.
Parameters
stateTState- The state passed to every attempt of the operation.
operationFunc<TState, CancellationToken, Task>- The operation to run. It receives
stateandcancellationToken. cancellationTokenCancellationToken optional- A token for canceling the operation and the waits between attempts (optional).
Returns
- Task
- A task that completes when the operation succeeds.
Exceptions
- ArgumentNullException
- Thrown, before a task is returned, if
operationisnull. - OperationCanceledException
- Thrown if
cancellationTokenis canceled while waiting before a retry.
Remarks
When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.
Pass the values that the operation needs as state and use an operation that captures no variables, such as a static lambda; the compiler then reuses one delegate instance, so the call allocates no closure. Use a tuple to pass several values.
ExecuteAsync<TState, T>(TState, Func<TState, CancellationToken, Task<T>>, CancellationToken)
public Task<T> ExecuteAsync<TState, T>(TState state, Func<TState, CancellationToken, Task<T>> operation, CancellationToken cancellationToken = default)Type Parameters
TState- The type of the state passed to the operation.
T- The type of the value the operation returns.
Parameters
stateTState- The state passed to every attempt of the operation.
operationFunc<TState, CancellationToken, Task<T>>- The operation to run. It receives
stateandcancellationToken. cancellationTokenCancellationToken optional- A token for canceling the operation and the waits between attempts (optional).
Returns
- Task<T>
- A task that resolves to the value returned by the first successful run of the operation.
Exceptions
- ArgumentNullException
- Thrown, before a task is returned, if
operationisnull. - OperationCanceledException
- Thrown if
cancellationTokenis canceled while waiting before a retry.
Remarks
When an exception is not retried, or the strategy allows no more retries, the last exception is rethrown with its original stack trace.
Pass the values that the operation needs as state and use an operation that captures no variables, such as a static lambda; the compiler then reuses one delegate instance, so the call allocates no closure. Use a tuple to pass several values.
OnRetry(Action<RetryContext>)
public RetryPolicy OnRetry(Action<RetryContext> handler)Parameters
handlerAction<RetryContext>- The handler, which receives the failed attempt and the delay that execution waits before the retry.
Returns
- RetryPolicy
- A new policy that invokes the handlers of this policy and then
handler.
Exceptions
- ArgumentNullException
- Thrown if
handlerisnull.
Remarks
OverrideDelay(Func<RetryContext, TimeSpan>)
public RetryPolicy OverrideDelay(Func<RetryContext, TimeSpan> delay)Parameters
delayFunc<RetryContext, TimeSpan>- A function that receives the failed attempt, whose RetryContext.Delay is the delay that the strategy proposes, and returns the nonnegative delay to wait. Return RetryContext.Delay to keep the proposed delay.
Returns
- RetryPolicy
- A new policy whose delays
delayselects. It replaces any delay override of this policy.
Exceptions
- ArgumentNullException
- Thrown if
delayisnull.
Remarks
The override runs only after the strategy allows a retry, and its delay replaces the proposed delay after all strategy modifiers, so it can exceed a delay cap or the time left under an elapsed-time limit. Enforce any required deadline in the override or with the caller's cancellation token.
A negative delay throws ArgumentOutOfRangeException from the execution, without a retry. A delay longer than int.MaxValue milliseconds stops retrying, as when the strategy allows no more retries.
RetryOn(Func<Exception, bool>)
public RetryPolicy RetryOn(Func<Exception, bool> predicate)Parameters
Returns
- RetryPolicy
- A new policy that retries the exceptions this policy retries and the exceptions that
predicateselects.
Exceptions
- ArgumentNullException
- Thrown if
predicateisnull.
Remarks
RetryOn call limits retries to the exceptions it selects; later calls add to them. If predicate throws, the operation's exception propagates without a retry.RetryOn<TException>()
public RetryPolicy RetryOn<TException>()
where TException : ExceptionType Parameters
TException- The type of the exceptions to retry, including derived types.
Returns
- RetryPolicy
- A new policy that retries the exceptions this policy retries and the exceptions of type
TException.
Remarks
RetryOn call limits retries to the exceptions it selects; later calls add to them.RetryOn<TException>(Func<TException, bool>)
public RetryPolicy RetryOn<TException>(Func<TException, bool> predicate)
where TException : ExceptionType Parameters
TException- The type of the exceptions to retry, including derived types.
Parameters
predicateFunc<TException, bool>- A function that returns
truefor the exceptions of typeTExceptionto retry.
Returns
- RetryPolicy
- A new policy that retries the exceptions this policy retries and the exceptions that
predicateselects.
Exceptions
- ArgumentNullException
- Thrown if
predicateisnull.
Remarks
RetryOn call limits retries to the exceptions it selects; later calls add to them. If predicate throws, the operation's exception propagates without a retry.RetryOnResult<T>(Func<T, bool>)
T that also retries the results that satisfy a condition.public RetryPolicy<T> RetryOnResult<T>(Func<T, bool> predicate)Type Parameters
T- The type returned by the operations the new policy runs.
Parameters
Returns
- RetryPolicy<T>
- A new RetryPolicy<T> with this policy's strategy, retried exceptions, delay override, and retry handlers.
Exceptions
- ArgumentNullException
- Thrown if
predicateisnull.
Remarks
predicate selected it. The delay override and retry handlers of this policy receive a RetryContext for both exceptions and retried results.

A policy is immutable. Each configuration method returns a new policy and leaves the original unchanged, so a policy can be built once, stored, and shared by any number of concurrent executions. Each execution keeps its own retry count and elapsed time.
Without a call to a
RetryOnmethod, the policy retries every exception except an OperationCanceledException thrown after the caller's token is canceled, which is never retried. Call RetryOnResult<T>(Func<T, bool>) to also retry returned values; it returns a RetryPolicy<T> that keeps this policy's configuration.Callbacks run on the execution path. If an exception classifier throws, the operation's exception propagates as if it was not retried; an exception from a delay override or retry handler propagates in place of the operation's outcome, and the operation is not retried.