| | | 1 | | namespace Intentum.Runtime.Resilience.Retry; |
| | | 2 | | |
| | | 3 | | public sealed class MemoryRetryPolicy : IRetryPolicy |
| | | 4 | | { |
| | | 5 | | private readonly RetryOptions _options; |
| | | 6 | | |
| | 6 | 7 | | public MemoryRetryPolicy(RetryOptions options) |
| | 6 | 8 | | { |
| | 6 | 9 | | _options = options; |
| | 6 | 10 | | } |
| | | 11 | | |
| | | 12 | | public async Task<T> ExecuteAsync<T>(Func<CancellationToken, Task<T>> operation, CancellationToken cancellationToken |
| | 6 | 13 | | { |
| | 6 | 14 | | var attempts = 0; |
| | 13 | 15 | | while (true) |
| | 13 | 16 | | { |
| | 13 | 17 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 18 | | try |
| | 13 | 19 | | { |
| | 13 | 20 | | attempts++; |
| | 13 | 21 | | return await operation(cancellationToken); |
| | | 22 | | } |
| | 11 | 23 | | catch (Exception) when (attempts <= _options.MaxRetries) |
| | 8 | 24 | | { |
| | 8 | 25 | | var delay = CalculateDelay(attempts); |
| | 8 | 26 | | await Task.Delay(delay, cancellationToken); |
| | 7 | 27 | | } |
| | 7 | 28 | | } |
| | 2 | 29 | | } |
| | | 30 | | |
| | | 31 | | private TimeSpan CalculateDelay(int attempt) |
| | 8 | 32 | | { |
| | 8 | 33 | | return _options.Backoff switch |
| | 8 | 34 | | { |
| | 0 | 35 | | RetryBackoffType.Constant => _options.BaseDelay, |
| | 0 | 36 | | RetryBackoffType.Linear => _options.BaseDelay * attempt, |
| | 8 | 37 | | RetryBackoffType.Exponential => TimeSpan.FromMilliseconds( |
| | 8 | 38 | | _options.BaseDelay.TotalMilliseconds * Math.Pow(2, attempt - 1)), |
| | 0 | 39 | | _ => _options.BaseDelay |
| | 8 | 40 | | }; |
| | 8 | 41 | | } |
| | | 42 | | } |