|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Text; |
| 4 | + |
| 5 | +namespace Shared.IntegrationTesting |
| 6 | +{ |
| 7 | + using System.Threading; |
| 8 | + using System.Threading.Tasks; |
| 9 | + |
| 10 | + public static class Retry |
| 11 | + { |
| 12 | + #region Fields |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// The default retry for |
| 16 | + /// </summary> |
| 17 | + private static readonly TimeSpan DefaultRetryFor = TimeSpan.FromSeconds(60); |
| 18 | + |
| 19 | + /// <summary> |
| 20 | + /// The default retry interval |
| 21 | + /// </summary> |
| 22 | + private static readonly TimeSpan DefaultRetryInterval = TimeSpan.FromSeconds(5); |
| 23 | + |
| 24 | + #endregion |
| 25 | + |
| 26 | + #region Methods |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Fors the specified action. |
| 30 | + /// </summary> |
| 31 | + /// <param name="action">The action.</param> |
| 32 | + /// <param name="retryFor">The retry for.</param> |
| 33 | + /// <param name="retryInterval">The retry interval.</param> |
| 34 | + /// <returns></returns> |
| 35 | + public static async Task For(Func<Task> action, |
| 36 | + TimeSpan? retryFor = null, |
| 37 | + TimeSpan? retryInterval = null) |
| 38 | + { |
| 39 | + DateTime startTime = DateTime.Now; |
| 40 | + Exception lastException = null; |
| 41 | + |
| 42 | + if (retryFor == null) |
| 43 | + { |
| 44 | + retryFor = Retry.DefaultRetryFor; |
| 45 | + } |
| 46 | + |
| 47 | + while (DateTime.Now.Subtract(startTime).TotalMilliseconds < retryFor.Value.TotalMilliseconds) |
| 48 | + { |
| 49 | + try |
| 50 | + { |
| 51 | + await action().ConfigureAwait(false); |
| 52 | + lastException = null; |
| 53 | + break; |
| 54 | + } |
| 55 | + catch (Exception e) |
| 56 | + { |
| 57 | + lastException = e; |
| 58 | + |
| 59 | + // wait before retrying |
| 60 | + Thread.Sleep(retryInterval ?? Retry.DefaultRetryInterval); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + if (lastException != null) |
| 65 | + { |
| 66 | + throw lastException; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + #endregion |
| 71 | + } |
| 72 | +} |
0 commit comments