Skip to content

Instantly share code, notes, and snippets.

@gazlu
Created December 10, 2013 05:44
Show Gist options
  • Save gazlu/7886208 to your computer and use it in GitHub Desktop.
Save gazlu/7886208 to your computer and use it in GitHub Desktop.
Retry logic in c#, for max number of attempts and for expected value.
public class Retrier<TResult>
{
/// <summary>
/// Retry to perform an operation/function
/// </summary>
/// <param name="func">Function to retry</param>
/// <param name="maxRetries">Maximum retires</param>
/// <param name="delayInMilliseconds">Delay on millies, 0 by default</param>
/// <returns>Result of the Function</returns>
public TResult TryBool(Func<TResult> func, int maxRetries, int delayInMilliseconds = 0)
{
TResult returnValue = default(TResult);
int numTries = 0;
bool succeeded = false;
while (numTries < maxRetries)
{
try
{
returnValue = func();
succeeded = returnValue != null ? bool.Parse(returnValue.ToString()) : false;
}
catch (Exception)
{
//todo: figure out what to do here
}
finally
{
numTries++;
}
if (succeeded)
return returnValue;
System.Threading.Thread.Sleep(delayInMilliseconds);
}
return default(TResult);
}
/// <summary>
/// Retry to perform an operation/function
/// </summary>
/// <param name="func">Function to retry</param>
/// <param name="maxRetries">Maximum retires</param>
/// <param name="expectedValue">Retry untill we get expected value (for max number of retries)</param>
/// <param name="delayInMilliseconds">Delay on millies, 0 by default</param>
/// <returns>Result of the Function</returns>
public TResult Try(Func<TResult> func, int maxRetries, TResult expectedValue, int delayInMilliseconds = 0)
{
TResult returnValue = default(TResult);
int numTries = 0;
bool succeeded = false;
while (numTries < maxRetries)
{
try
{
returnValue = func();
succeeded = returnValue.Equals(expectedValue);
}
catch (Exception)
{
//todo: figure out what to do here
}
finally
{
numTries++;
}
if (succeeded)
return returnValue;
System.Threading.Thread.Sleep(delayInMilliseconds);
}
return default(TResult);
}
}
@icalvo
Copy link

icalvo commented Oct 31, 2014

I solved this same problem recently, in a very similar way, although I created a slightly more generic version, see https://gist.github.com/icalvo/3f5602f7e868e7a00690. I've taken the liberty of reimplementing one of your functions using my retrier, just to prove myself that is flexible enough.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment