Created
October 24, 2014 13:37
-
-
Save KennyBu/ac56371b1666a949daf8 to your computer and use it in GitHub Desktop.
C# Retry
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 Retry | |
{ | |
public static void Do( | |
Action action, | |
TimeSpan retryInterval, | |
int retryCount = 3) | |
{ | |
Do<object>(() => | |
{ | |
action(); | |
return null; | |
}, retryInterval, retryCount); | |
} | |
public static T Do<T>( | |
Func<T> action, | |
TimeSpan retryInterval, | |
int retryCount = 3) | |
{ | |
var exceptions = new List<Exception>(); | |
for (var retry = 0; retry <= retryCount; retry++) | |
{ | |
try | |
{ | |
return action(); | |
} | |
catch (Exception ex) | |
{ | |
exceptions.Add(ex); | |
Thread.Sleep(retryInterval); | |
} | |
} | |
throw new AggregateException(exceptions); | |
} | |
} |
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
//Example Usage | |
var client = new client(); | |
var waitTime = 2; | |
var numberOfRetries = 3; | |
var result = Retry.Do(() => client.CallWebService(parameter1, parameter2) | |
, TimeSpan.FromSeconds(waitTime) | |
, numberOfRetries); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment