Last active
August 29, 2015 14:07
-
-
Save msajid/aef9fd17af51a66ed684 to your computer and use it in GitHub Desktop.
a custom retry helper class with Action and Func of T.
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
using System; | |
using System.Threading; | |
namespace RetrySolution | |
{ | |
public static class RetryManager | |
{ | |
private const int RetryCount = 3; | |
private const int RetryTimeoutInMillis = 100; | |
public static void TryExecute(Action action) | |
{ | |
if (action == null) return; | |
var numberOfRetries = RetryCount; | |
do | |
{ | |
try | |
{ | |
action(); | |
return; | |
} | |
catch (TimeoutException ex) | |
{ | |
if (numberOfRetries == 0) | |
{ | |
throw; | |
} | |
Thread.Sleep(RetryTimeoutInMillis); | |
} | |
catch (Exception ex) | |
{ | |
if (numberOfRetries == 0) | |
{ | |
throw; | |
} | |
Thread.Sleep(RetryTimeoutInMillis); | |
} | |
} | |
while (numberOfRetries-- > 0); | |
} | |
public static T TryExecute<T>(Func<T> func) | |
{ | |
if (func == null) return default(T); | |
var numberOfRetries = RetryCount; | |
do | |
{ | |
try | |
{ | |
return func(); | |
} | |
catch (TimeoutException ex) | |
{ | |
if (numberOfRetries == 0) | |
{ | |
throw; | |
} | |
Thread.Sleep(RetryTimeoutInMillis); | |
} | |
catch (Exception ex) | |
{ | |
if (numberOfRetries == 0) | |
{ | |
throw; | |
} | |
Thread.Sleep(RetryTimeoutInMillis); | |
} | |
} | |
while (numberOfRetries-- > 0); | |
return default(T); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment