Created
October 1, 2014 08:59
-
-
Save harrybiscuit/5206d3a516d3d1530793 to your computer and use it in GitHub Desktop.
A simple retry mechanism for C#
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
// This is not my code but I put it here so I can remember where to get it when I need it. | |
//http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic | |
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 (int retry = 0; retry < retryCount; retry++) { | |
try { | |
return action(); | |
} | |
catch (Exception ex) { | |
exceptions.Add(ex); | |
Thread.Sleep(retryInterval); | |
} | |
} | |
exceptions.Add(new Exception(string.Format("Method call failed after {0} retries with {1} second intervals.",retryCount,retryInterval ))); | |
throw new AggregateException(exceptions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sikc tell how do it jack