-
-
Save pelengami/c50776db9c612a643490536e98638f0f to your computer and use it in GitHub Desktop.
Repeater
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
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