Class CircuitBreakerPolicy
- Namespace
- LMKit.Agents.Resilience
- Assembly
- LM-Kit.NET.dll
A resilience policy that implements the circuit breaker pattern.
Prevents cascade failures by "tripping" the circuit after a threshold of failures, rejecting subsequent calls until a recovery period elapses.
public sealed class CircuitBreakerPolicy : IResiliencePolicy
- Inheritance
-
CircuitBreakerPolicy
- Implements
- Inherited Members
- Extension Methods
Examples
var breaker = new CircuitBreakerPolicy(
failureThreshold: 5,
recoveryTime: TimeSpan.FromSeconds(30));
try
{
var result = await breaker.ExecuteAsync(ct => agent.RunAsync("Hello", ct));
}
catch (CircuitBreakerOpenException)
{
Console.WriteLine("Service unavailable, try again later");
}
Remarks
Circuit States
- Closed: Normal operation, calls pass through.
- Open: Circuit is tripped, calls fail fast without execution.
- HalfOpen: Testing recovery, allowing one call through.
Constructors
- CircuitBreakerPolicy(int, TimeSpan?, TimeSpan?)
Initializes a new instance of the CircuitBreakerPolicy class.
Properties
- FailureCount
Gets the current failure count.
- Name
Gets the name of this policy.
- State
Gets the current circuit state.
Methods
- ExecuteAsync<T>(Func<ResilienceContext, CancellationToken, Task<T>>, ResilienceContext, CancellationToken)
Executes an action with this policy and context.
- ExecuteAsync<T>(Func<CancellationToken, Task<T>>, CancellationToken)
Executes an action with this policy applied.
- HandleException(Func<Exception, bool>)
Sets a predicate to determine which exceptions count toward the threshold.
- OnStateChange(Action<CircuitState, CircuitState>)
Sets a callback for state changes.
- Reset()
Manually resets the circuit breaker to closed state.
- Trip()
Manually trips the circuit breaker to open state.