Created
December 10, 2013 05:44
-
-
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.
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 characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.