Skip to content

Resilience

The Resilience type is a sealed partial record in the NResilience namespace. It is immutable; use the with expression to derive a variant.

Presets

NResilience provides several presets for common scenarios:

PresetBehavior
Resilience.NonePassthrough. Executes one attempt with no bounds or budget. The executor returns the callback's own task.
Resilience.DefaultThree attempts, 30-second deadline, 10-second attempt timeout, Backoff.Default, and Classifier.Default.
Resilience.HttpA Default policy configured with Classifier.Http and Name = "http".

Properties

PropertyTypeDefaultDescription
Attemptsint3The total number of attempts, including the first.
DeadlineTimeSpan30 sThe wall-clock budget for the entire call. Use Timeout.InfiniteTimeSpan to disable the bound.
AttemptTimeoutTimeSpan10 sThe maximum duration for a single attempt. The effective value is the minimum of this property and the remaining time on the deadline.
BackoffBackoffBackoff.DefaultThe delay between attempts.
ClassifyClassifierClassifier.DefaultThe logic used to classify outcomes.
BreakerBreaker?nullThe circuit breaker. A null value indicates no breaking is active.
BudgetRetryBudget?nullThe retry budget. A null value creates an automatic budget private to this policy instance.
BeforeAttemptFunc<NextAttempt, Task>?nullA function that runs before every attempt, including the first.
OnEventAction<CallEvent>?nullThe telemetry listener. If null, no events are raised and no performance cost is incurred.
Namestring?nullA name used in diagnostics and telemetry tags.
TimeTimeProviderTimeProvider.SystemThe clock used for timing. Use the system provider in production.

Methods

The Resilience record provides methods to execute calls with the defined resilience policy.

MethodReturn Type
RunAsync<T>(Func<CancellationToken, Task<T>>, CancellationToken)ValueTask<T>
RunAsync(Func<CancellationToken, Task>, CancellationToken)ValueTask
RunAsync<TState, T>(Func<TState, CancellationToken, Task<T>>, TState, CancellationToken)ValueTask<T>
RunAsync<TState>(Func<TState, CancellationToken, Task>, TState, CancellationToken)ValueTask
TryRunAsync<T>(…)ValueTask<CallResult<T>>
TryRunAsync(…)ValueTask<CallResult>
TryRunAsync<TState, T>(…)ValueTask<CallResult<T>>
TryRunAsync<TState>(…)ValueTask<CallResult>
Validate()void

Execution behavior

RunAsync methods throw the original exception with its stack trace intact, or one of the exceptions defined by the library. TryRunAsync methods return a CallResult and always materialize the attempt log.

Cancellation tokens

Every method signature includes two different CancellationToken parameters:

  1. The callback token: Passed to the execution callback. It is cancelled when the attempt hits its AttemptTimeout or when the caller's token is cancelled.
  2. The caller token: The trailing parameter. It cancels the entire operation, including all retries.

For more information, see the cancellation contract.

State and allocation

The TState overloads allow you to use static callbacks, which avoids closure allocations. These overloads provide the same functionality as the closure-based forms.

Validation

The Validate method checks the policy configuration for errors and throws a ResilienceConfigurationException if any are found. Validation does not occur at construction; it happens when you call Validate explicitly, during eager DI registration, or lazily on the first execution of a policy instance.

NextAttempt

The NextAttempt readonly struct is passed to BeforeAttempt and Backoff.Custom.

MemberDescription
NumberThe 1-based index of the attempt (1 for the first attempt).
PreviousVerdictThe classification of the previous attempt. Defaults to Verdict.Ok for the first attempt.
PreviousExceptionThe exception thrown by the previous attempt, if any.
RemainingThe time remaining on the deadline, or Timeout.InfiniteTimeSpan.
CancellationTokenThe caller's cancellation token.

Equality

Two policies are considered equal if all their properties are equal. Breaker and RetryBudget are compared by reference because they are live state objects rather than configuration. ToString returns the policy configuration.

Released under the MIT License.