Skip to content

Instantly share code, notes, and snippets.

@deadlydog
Created December 15, 2021 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deadlydog/3780dc8b966575aed94b4ee5d6f148a1 to your computer and use it in GitHub Desktop.
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
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