static class Util { /// /// Retries the specified code block. /// /// /// The number of retries to attempt before failing /// The number of seconds to wait between retries /// The error return. /// The Exception handling method /// The code. /// /// /// OK, this has very weird semantics. A call will look something like this: /// "Error", /// AppLog.Log, /// ( ) => /// { /// Console.WriteLine(DateTime.Now.ToLongTimeString()); /// if ((DateTime.Now.Second & 7) != 7) /// throw new Exception("Bad"); /// return DateTime.Now.ToString(); /// }); /// ]]> /// /// /// The third parameter is a function (or lambda expresion) taking no parameters, and returning /// the value to return in case of failure. (it done as a function to avoid evaluating it unless needed). /// /// /// The (optional) fourth parameter is a function (or lambda expresion) taking an exception as a parameter, and /// returning nothing. Can be used to log the exception on failure. /// /// /// The last parameter is a function (or lambda expresion) taking no parameters, which preforms the /// actual work which may need to be retried. /// /// /// static public T Retry(int retries, int secsDelay, Func errorReturn, Action onError, Func code) { Exception ex = null; do { try { return code(); } catch (Exception dde) { ex = dde; retries--; Thread.Sleep(secsDelay * 1000); } } while (retries > 0); onError(ex); return errorReturn(); } static public T Retry(int retries, int secsDelay, Func errorReturn, Func code) { return Retry(retries, secsDelay, errorReturn, ex => { }, code); } }