Last active
May 2, 2017 17:40
-
-
Save 0x49D1/0dcfa882aa26241a9bd09068a70fc366 to your computer and use it in GitHub Desktop.
Polly sample
This file contains hidden or 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
using System; | |
using Polly; | |
namespace ConsoleApp1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Retry a specified number of times, using a function to | |
// calculate the duration to wait between retries based on | |
// the current retry attempt (allows for exponential backoff) | |
// In this case will wait for | |
// 2 ^ 1 = 2 seconds then | |
// 2 ^ 2 = 4 seconds then | |
// 2 ^ 3 = 8 seconds then | |
// 2 ^ 4 = 16 seconds | |
try | |
{ | |
var retryPolicy = Polly.Policy.Handle<DivideByZeroException>(e => | |
{ | |
// Here we can do some exception handling | |
Console.WriteLine("Handling Devide by zero exception"); | |
return true; | |
}).WaitAndRetry(4, retryAttempt => | |
{ | |
Console.WriteLine($"Retrying attempt {retryAttempt}"); | |
return TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)); | |
} | |
); | |
retryPolicy.Execute(Divide); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"Handling the exception {ex.ToString()}"); // Dumb handle not to crash | |
} | |
Console.ReadKey(); | |
} | |
private static void Divide() | |
{ | |
int a = 10; | |
int b = 0; | |
var c = a / b; // 0 divide exception! | |
// todo uncomment this line to see that any other type of exception will be just not handled by our policy | |
//throw new AccessViolationException("TEST"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment