<PackageReference Include="Polly" Version="4.1.2" />

CircuitBreakerEngine

using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Polly.CircuitBreaker { internal class CircuitBreakerEngine { internal static void Implementation(Action action, Context context, IEnumerable<ExceptionPredicate> shouldHandlePredicates, ICircuitController breakerController) { ThrowIfCircuitBroken(breakerController); try { action(); breakerController.OnActionSuccess(context); } catch (Exception ex2) { Exception ex; Exception ex3 = ex = ex2; if (!shouldHandlePredicates.Any((ExceptionPredicate predicate) => predicate(ex))) throw; breakerController.OnActionFailure(ex, context); throw; } } private static void ThrowIfCircuitBroken(ICircuitController breakerController) { switch (breakerController.CircuitState) { case CircuitState.Closed: case CircuitState.HalfOpen: break; case CircuitState.Open: throw new BrokenCircuitException("The circuit is now open and is not allowing calls.", breakerController.LastException); case CircuitState.Isolated: throw new IsolatedCircuitException("The circuit is manually held open and is not allowing calls."); default: throw new InvalidOperationException("Unhandled CircuitState."); } } internal static async Task ImplementationAsync(Func<CancellationToken, Task> action, Context context, IEnumerable<ExceptionPredicate> shouldHandlePredicates, ICircuitController breakerController, CancellationToken cancellationToken, bool continueOnCapturedContext) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfCircuitBroken(breakerController); try { await action(cancellationToken).ConfigureAwait(continueOnCapturedContext); breakerController.OnActionSuccess(context); } catch (Exception ex2) { Exception ex = ex2; if (cancellationToken.IsCancellationRequested) { if (ex is OperationCanceledException && ((OperationCanceledException)ex).CancellationToken == cancellationToken) throw; cancellationToken.ThrowIfCancellationRequested(); } if (!shouldHandlePredicates.Any((ExceptionPredicate predicate) => predicate(ex))) throw; breakerController.OnActionFailure(ex, context); throw; } } } }