Occasionally I have a need to retry an operation several times before giving up. My code is like:
int retries = 3;
while(true) {
try {
DoSomething();
Implemented LBushkin's answer in the latest fashion:
public static async Task Do(Func task, TimeSpan retryInterval, int maxAttemptCount = 3)
{
var exceptions = new List();
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
try
{
if (attempted > 0)
{
await Task.Delay(retryInterval);
}
await task();
return;
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
public static async Task Do(Func> task, TimeSpan retryInterval, int maxAttemptCount = 3)
{
var exceptions = new List();
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
try
{
if (attempted > 0)
{
await Task.Delay(retryInterval);
}
return await task();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
and to use it:
await Retry.Do([TaskFunction], retryInterval, retryAttempts);
whereas the function [TaskFunction]
can either be Task
or just Task
.