Created
December 15, 2021 04:16
-
-
Save deadlydog/3780dc8b966575aed94b4ee5d6f148a1 to your computer and use it in GitHub Desktop.
C# generic function to execute any function, retrying if an exception is thrown
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
public static T InvokeMethodWithRetries<T>(Func<T> method, int maxNumberOfAttempts = 5) | |
{ | |
int numberOfAttempts = 0; | |
while (numberOfAttempts < maxNumberOfAttempts) | |
{ | |
try | |
{ | |
return method.Invoke(); | |
} | |
catch (Exception ex) | |
{ | |
numberOfAttempts++; | |
_log.Warn($"Attempt number '{numberOfAttempts}' failed. Exception: {ex}"); | |
if (numberOfAttempts >= maxNumberOfAttempts) | |
{ | |
throw; | |
} | |
int numberOfSecondsToWait = numberOfAttempts * 5; | |
_log.Debug($"Waiting '{numberOfSecondsToWait}' seconds before trying again."); | |
System.Threading.Thread.Sleep(numberOfSecondsToWait * 1000); | |
} | |
} | |
return default; | |
} | |
// Example of calling function. | |
// ReturnValue returnedValue = InvokeMethodWithRetries<ReturnValue>(() => GetSomeValue()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment