Last active
August 29, 2015 13:57
-
-
Save aliostad/9764497 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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