Skip to content

Instantly share code, notes, and snippets.

@bitsprint
Created August 9, 2018 08:21
Show Gist options
  • Save bitsprint/281bc09b6b0d3d7d621c70985414709a to your computer and use it in GitHub Desktop.
Save bitsprint/281bc09b6b0d3d7d621c70985414709a to your computer and use it in GitHub Desktop.
Retry Utility
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);
}
}
@bitsprint
Copy link
Author

bitsprint commented Aug 9, 2018

Usage (using LinqPad):

`
try
{
RetryUtility.Do(() =>
{
var result = DateTime.Now.Ticks % 2;

		if (result == 1)
			throw new InvalidOperationException();

		result.Dump();
	});
}
catch (AggregateException ex)
{
	foreach (var exception in ex.InnerExceptions)
	{
		exception.Message.Dump();			
	}	
}

try
{
	var retryResult = RetryUtility.Do<long>(() =>
	{
		var result = DateTime.Now.Ticks % 2;

		if (result == 1)
			throw new InvalidOperationException();

		return result;
	});

	retryResult.Dump();
}
catch (AggregateException ex)
{
	foreach (var exception in ex.InnerExceptions)
	{
		exception.Message.Dump();
	}
}

`

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