Created
July 20, 2019 16:28
Revisions
-
FusRoDah061 created this gist
Jul 20, 2019 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,50 @@ /* https://stackoverflow.com/questions/1563191/cleanest-way-to-write-retry-logic/1563234?fbclid=IwAR1xkK60U07JQP8NZ0h61mWuF21AOWEfGXLrDs94PuvLI0xo7HMkdsWSQcs#1563234 Usage: Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1)); Or Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1)); Or int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4); */ public static class Retry { public static void Do( Action action, TimeSpan retryInterval, int maxAttemptCount = 3) { Do<object>(() => { action(); return null; }, retryInterval, maxAttemptCount); } public static T Do<T>( Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3) { var exceptions = new List<Exception>(); for (int attempted = 0; attempted < maxAttemptCount; attempted++) { try { if (attempted > 0) { Thread.Sleep(retryInterval); } return action(); } catch (Exception ex) { exceptions.Add(ex); } } throw new AggregateException(exceptions); } }