private static MultiTryOptions <T> Validate <T>(Delegate function, MultiTryOptions <T> options) { if (function == null) { throw new ArgumentNullException(nameof(function), "MultiTry: function must be set!"); } if (options == null) { options = MultiTryOptions <T> .Default; } options.Validate(); return(options); }
/// <summary> /// Retry action repeatedly /// <param name="action">Action to execute</param> /// <param name="options">Retry options. Can be null, see <see cref="MultiTryOptions"/> for defaults</param> /// </summary> public static void Try(Action action, MultiTryOptions options = null) { if (action == null) { throw new ArgumentNullException(nameof(action), "MultiTry: action must be set!"); } if (options == null) { options = MultiTryOptions.Default; } options.Validate(); var i = 0; Exception lastException; do { try { action.Invoke(); return; } catch (Exception ex) when(options.ExceptionFilter(ex)) { lastException = ex; if (options.OnException?.Invoke(ex, i) == false) { break; } } if (options.Delay > 0) { Thread.Sleep(options.Delay); } i++; } while (i < options.TryCount); options.OnFinalFailure?.Invoke(lastException); }