Skip to content

Instantly share code, notes, and snippets.

@DavidBrower
Last active February 23, 2016 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBrower/a608e00960abad5b0a9f to your computer and use it in GitHub Desktop.
Save DavidBrower/a608e00960abad5b0a9f to your computer and use it in GitHub Desktop.
Polly Circuitbreaker
public interface ICircuitBreaker
{
TResult Execute(Func action);
void Execute(Action action);
}
public interface ICircuitBreakerSettings
{
int BreakOnNumberOfExceptions { get; }
int BreakCircuitForSeconds { get; }
}
public class PollyCircuitBreaker : ICircuitBreaker
{
private readonly Policy _policy;
public PollyCircuitBreaker(ICircuitBreakerSettings settings)
{
try
{
_policy = Policy
.Handle<Exception>()
.CircuitBreaker(settings.BreakOnNumberOfExceptions,
TimeSpan.FromSeconds(settings.BreakCircuitForSeconds));
}
catch (Exception ex)
{
_policy = null;
//Log policy configuration issue
}
}
public TResult Execute<TResult>(Func<TResult> action)
{
if (_policy == null)
{
return action.Invoke();
}
else
{
try
{
return _policy.Execute(action);
}
catch (BrokenCircuitException ex)
{
throw new CircuitBrokenException("Broken circuit", ex);
}
}
}
public void Execute(Action action)
{
if (_policy == null)
{
action.Invoke();
}
else
{
try
{
_policy.Execute(action);
}
catch (BrokenCircuitException ex)
{
throw new CircuitBrokenException("Broken circuit", ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment