Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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