示例#1
0
        public static async Task RetryAsync(IDbRetryPolicy policy, Func <Task> action, CancellationToken cancellationToken = default)
        {
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            IEnumerator <TimeSpan> intervals = null;

            while (true)
            {
                try
                {
                    await action();

                    return;
                }
                catch (Exception ex) when(policy.ShouldRetry(ex))
                {
                    if (intervals == null)
                    {
                        intervals = policy.Strategy.GetIntervals().GetEnumerator();
                    }
                    if (!intervals.MoveNext())
                    {
                        throw;
                    }
                    await Task.Delay(intervals.Current, cancellationToken);
                }
            }
        }
示例#2
0
        public static T Retry <T>(IDbRetryPolicy policy, Func <T> action)
        {
            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            IEnumerator <TimeSpan> intervals = null;

            while (true)
            {
                try
                {
                    return(action());
                }
                catch (Exception ex) when(policy.ShouldRetry(ex))
                {
                    if (intervals == null)
                    {
                        intervals = policy.Strategy.GetIntervals().GetEnumerator();
                    }
                    if (!intervals.MoveNext())
                    {
                        throw;
                    }
                    Thread.Sleep(intervals.Current);
                }
            }
        }