Created
August 9, 2018 08:21
-
-
Save bitsprint/281bc09b6b0d3d7d621c70985414709a to your computer and use it in GitHub Desktop.
Retry Utility
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 RetryUtility | |
{ | |
public void Do(Action action, int retryInterval = 100, int maxAttemptCount = 3) | |
{ | |
Do<object>(() => | |
{ | |
action(); | |
return null; | |
}, retryInterval, maxAttemptCount); | |
} | |
public T Do<T>(Func<T> action, int retryInterval = 100, int maxAttemptCount = 3) | |
{ | |
var exceptions = new List<Exception>(); | |
for (int attempted = 0; attempted < maxAttemptCount; attempted++) | |
{ | |
try | |
{ | |
if (attempted > 0) | |
{ | |
Thread.Sleep(retryInterval); | |
} | |
return action(); | |
} | |
catch (Exception ex) | |
{ | |
exceptions.Add(ex); | |
} | |
} | |
throw new AggregateException(exceptions); | |
} | |
public async Task DoAsync(Action action, int retryInterval = 100, int maxAttemptCount = 3) | |
{ | |
await DoAsync<object>(() => | |
{ | |
action(); | |
return null; | |
}, retryInterval, maxAttemptCount); | |
} | |
public async Task<T> DoAsync<T>(Func<Task<T>> action, int retryInterval = 100, int maxAttemptCount = 3) | |
{ | |
var exceptions = new List<Exception>(); | |
for (int attempted = 0; attempted < maxAttemptCount; attempted++) | |
{ | |
try | |
{ | |
if (attempted > 0) | |
{ | |
Thread.Sleep(retryInterval); | |
} | |
return await action(); | |
} | |
catch (Exception ex) | |
{ | |
exceptions.Add(ex); | |
} | |
} | |
throw new AggregateException(exceptions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage (using LinqPad):
`
try
{
RetryUtility.Do(() =>
{
var result = DateTime.Now.Ticks % 2;
`