Skip to content

Instantly share code, notes, and snippets.

@pelengami
Created February 21, 2017 06:18
Show Gist options
  • Save pelengami/c50776db9c612a643490536e98638f0f to your computer and use it in GitHub Desktop.
Save pelengami/c50776db9c612a643490536e98638f0f to your computer and use it in GitHub Desktop.
Repeater
public static class Repeater
{
public static async Task DoInfinityAsync(Action action, TimeSpan interval, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
action();
await Task.Delay(interval, cancellationToken);
}
catch (TaskCanceledException)
{
return;
}
catch (Exception ex)
{
//log
return;
}
}
}
/// <exception cref="AggregateException"/>
public static async Task DoAsync(Action action, TimeSpan retryInterval, int retryCount = 3)
{
await DoAsync(() =>
{
action();
return default(object);
}, retryInterval, retryCount);
}
/// <exception cref="AggregateException"/>
public static async Task<T> DoAsync<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
{
var exceptions = new List<Exception>();
for (int retry = 0; retry < retryCount; retry++)
{
try
{
if (retry > 0)
await Task.Delay(retryInterval);
return 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