Occasionally I have a need to retry an operation several times before giving up. My code is like:
int retries = 3; while(true) { try { DoSomething();
For those who want to have both the option to retry on any exception or explicitly set the exception type, use this:
public class RetryManager { public void Do(Action action, TimeSpan interval, int retries = 3) { Try(() => { action(); return null; }, interval, retries); } public T Do(Func action, TimeSpan interval, int retries = 3) { return Try( action , interval , retries); } public T Do(Func action, TimeSpan interval, int retries = 3) where E : Exception { return Try( action , interval , retries); } public void Do(Action action, TimeSpan interval, int retries = 3) where E : Exception { Try(() => { action(); return null; }, interval, retries); } private T Try(Func action, TimeSpan interval, int retries = 3) where E : Exception { var exceptions = new List(); for (int retry = 0; retry < retries; retry++) { try { if (retry > 0) Thread.Sleep(interval); return action(); } catch (E ex) { exceptions.Add(ex); } } throw new AggregateException(exceptions); } }