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

Policy

public class Policy
Transient exception handling policies that can be applied to delegates
using Polly.Extensions; using System; using System.Diagnostics; using System.Threading.Tasks; namespace Polly { public class Policy { private readonly Action<Action> _exceptionPolicy; private readonly Func<Func<Task>, Task> _asyncExceptionPolicy; internal Policy(Action<Action> exceptionPolicy) { if (exceptionPolicy == null) throw new ArgumentNullException("exceptionPolicy"); _exceptionPolicy = exceptionPolicy; } [DebuggerStepThrough] public void Execute(Action action) { if (_exceptionPolicy == null) throw new InvalidOperationException("Please use the synchronous Retry, RetryForever, WaitAndRetry or CircuitBreaker methods when calling the synchronous Execute method."); _exceptionPolicy(action); } [DebuggerStepThrough] public TResult Execute<TResult>(Func<TResult> action) { if (_exceptionPolicy == null) throw new InvalidOperationException("Please use the synchronous Retry, RetryForever, WaitAndRetry or CircuitBreaker methods when calling the synchronous Execute method."); TResult result = (TResult)default(TResult); _exceptionPolicy(delegate { result = (TResult)action(); }); return (TResult)result; } public static PolicyBuilder Handle<TException>() where TException : Exception { ExceptionPredicate exceptionPredicate = (Exception exception) => exception is TException; return new PolicyBuilder(exceptionPredicate); } public static PolicyBuilder Handle<TException>(Func<TException, bool> exceptionPredicate) where TException : Exception { ExceptionPredicate exceptionPredicate2 = delegate(Exception exception) { if (exception is TException) return exceptionPredicate((TException)exception); return false; }; return new PolicyBuilder(exceptionPredicate2); } internal Policy(Func<Func<Task>, Task> asyncExceptionPolicy) { if (asyncExceptionPolicy == null) throw new ArgumentNullException("asyncExceptionPolicy"); _asyncExceptionPolicy = asyncExceptionPolicy; } [DebuggerStepThrough] public Task ExecuteAsync(Func<Task> action) { if (_asyncExceptionPolicy == null) throw new InvalidOperationException("Please use the asynchronous RetryAsync, RetryForeverAsync, WaitAndRetryAsync or CircuitBreakerAsync methods when calling the asynchronous Execute method."); return _asyncExceptionPolicy(action); } public async Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> action) { if (_asyncExceptionPolicy == null) throw new InvalidOperationException("Please use the asynchronous RetryAsync, RetryForeverAsync, WaitAndRetryAsync or CircuitBreakerAsync methods when calling the asynchronous Execute method."); TResult result = (TResult)default(TResult); await _asyncExceptionPolicy(async delegate { result = (TResult)(await Polly.Extensions.TaskExtensions.NotOnCapturedContext<TResult>(action())); }); return (TResult)result; } } }