Skip to content

Instantly share code, notes, and snippets.

@aliostad
Last active August 29, 2015 13:57
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 aliostad/9764497 to your computer and use it in GitHub Desktop.
Save aliostad/9764497 to your computer and use it in GitHub Desktop.
public static class CircuitBreakerExtensions
{
/// <summary>
///
/// </summary>
/// <param name="circuit">async work</param>
/// <param name="timeout">it abandons the work if not finished until this timeout</param>
/// <param name="finalTimeout">timeout for when the task runs for final time</param>
/// <param name="tries">number of times to try the work</param>
/// <param name="retryRemedy">after each unscuccessful retry, this will be called and the index will be passed</param>
public static bool CircuitBreaker(this Func<Task> circuit, TimeSpan timeout, TimeSpan finalTimeout, int tries = 3, Action<int> retryRemedy = null)
{
tries = Math.Max(1, tries);
var tried = 0;
while (tried < tries)
{
// offload to another thread to prevent deadlock
if (Task.Run(circuit).Wait(tried==tries-1 ? finalTimeout : timeout))
return true;
if (retryRemedy != null)
retryRemedy(tried);
tried++;
}
throw new TimeoutException("CircuitBreaker did not succeed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment