如何在满足某些条件之前重试

时间:2016-10-06 20:56:36

标签: c# .net visual-studio

我需要重试某个方法,直到它返回一个非空的Guid。

有一个很棒的answer根据是否有异常重试;但是,我想概括这个类能够处理任何指定的条件。

当前用法将执行特定次数的操作,直到没有例外:

Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));

或:

Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));

或:

int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);

如何修改此类,使其根据我传入的函数的返回值重试?

例如,如果我想重试,直到我的函数返回3:

Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1)).Until(3);

这意味着每1秒执行一次SomeFunctionThatCanFail(),直到SomeFunctionThatCanFail()= 3?

在满足条件之前,我如何概括Retry.Do的用法?

public static class Retry
{
   public static void Do(
       Action action,
       TimeSpan retryInterval,
       int retryCount = 3)
   {
       Do<object>(() => 
       {
           action();
           return null;
       }, retryInterval, retryCount);
   }

   public static T Do<T>(
       Func<T> action, 
       TimeSpan retryInterval,
       int retryCount = 3)
   {
       var exceptions = new List<Exception>();

       for (int retry = 0; retry < retryCount; retry++) //I would like to change this logic so that it will retry not based on whether there is an exception but based on the return value of Action
       {
          try
          { 
              if (retry > 0)
                  Thread.Sleep(retryInterval);
              return action();
          }
          catch (Exception ex)
          { 
              exceptions.Add(ex);
          }
       }

       throw new AggregateException(exceptions);
   }
}

4 个答案:

答案 0 :(得分:5)

如何创建以下界面:

public interface IRetryCondition<TResult>
{
     TResult Until(Func<TResult, bool> condition);
}

public class RetryCondition<TResult> : IRetryCondition<TResult>
{
     private TResult _value;
     private Func<IRetryCondition<TResult>> _retry;

     public RetryCondition(TResult value, Func<IRetryCondition<TResult>> retry)
     {
         _value = value;
         _retry = retry;
     }

     public TResult Until(Func<TResult, bool> condition)
     {
         return condition(_value) ? _value : _retry().Until(condition);
     }
}

然后,您将更新Retry静态类:

public static class Retry
{
    // This method stays the same
    // Returning an IRetryCondition does not make sense in a "void" action
    public static void Do(
       Action action,
       TimeSpan retryInterval,
       int retryCount = 3)
    {
        Do<object>(() => 
        {
            action();
            return null;
        }, retryInterval, retryCount);
    }

    // Return an IRetryCondition<T> instance
    public static IRetryCondition<T> Do<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)
                  Thread.Sleep(retryInterval);

               // We return a retry condition loaded with the return value of action() and telling it to execute this same method again if condition is not met.
               return new RetryCondition<T>(action(), () => Do(action, retryInterval, retryCount));
            }
            catch (Exception ex)
            { 
                exceptions.Add(ex);
            }
        }

        throw new AggregateException(exceptions);
    }
}

您将能够实现以下目标:

int result = Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1)).Until(r => r == 3);

更实用的方法

我试图想出一个更“面向功能”的解决方案(有点类似于LINQ):

首先,我们将有两个用于执行操作的接口:

public interface IRetryResult
{
    void Execute();
}

public interface IRetryResult<out TResult>
{
    TResult Execute();
}

然后,我们需要两个接口来配置重试操作:

public interface IRetryConfiguration : IRetryResult
{
    IRetryConfiguration Times(int times);
    IRetryConfiguration Interval(TimeSpan interval);
}

public interface IRetryConfiguration<out TResult> : IRetryResult<TResult>
{
    IRetryConfiguration<TResult> Times(int times);
    IRetryConfiguration<TResult> Interval(TimeSpan interval);
    IRetryConfiguration<TResult> Until(Function<TResult, bool> condition);
}

最后,我们需要两个接口的两个实现:

public class ActionRetryConfiguration : IRetryConfiguration
{
    private readonly Action _action;
    private readonly int? _times;
    private readonly TimeSpan? _interval;

    public ActionRetryConfiguration(Action action, int? times, TimeSpan? interval)
    {
        _action = action;
        _times = times;
        _interval = interval;
    }

    public void Execute()
    {
        Execute(_action, _times, _interval);
    }

    private void Execute(Action action, int? times, TimeSpan? interval)
    {
        action();
        if (times.HasValue && times.Value <= 1) return;
        if (times.HasValue && interval.HasValue) Thread.Sleep(interval.Value);
        Execute(action, times - 1, interval);
    }

    public IRetryConfiguration Times(int times)
    {
        return new ActionRetryConfiguration(_action, times, _interval);
    }

    public IRetryConfiguration Interval(TimeSpan interval)
    {
        return new ActionRetryConfiguration(_action, _times, interval);
    }
}


public class FunctionRetryConfiguration<TResult> : IRetryConfiguration<TResult>
{
    private readonly Func<TResult> _function;
    private readonly int? _times;
    private readonly TimeSpan? _interval;
    private readonly Func<TResult, bool> _condition;

    public FunctionRetryConfiguration(Func<TResult> function, int? times, TimeSpan? interval, Func<TResult, bool> condition)
    {
        _function = function;
        _times = times;
        _interval = interval;
        _condition = condition;
    }

    public TResult Execute()
    {
        return Execute(_function, _times, _interval, _condition);
    }

    private TResult Execute(Func<TResult> function, int? times, TimeSpan? interval, Func<TResult, bool> condition)
    {
        TResult result = function();
        if (condition != null && condition(result)) return result;
        if (times.HasValue && times.Value <= 1) return result;
        if ((times.HasValue || condition != null) && interval.HasValue) Thread.Sleep(interval.Value);
        return Execute(function, times - 1, interval, condition);
    }

    public IRetryConfiguration<TResult> Times(int times)
    {
        return new FunctionRetryConfiguration<TResult>(_function, times, _interval, _condition);
    }

    public IRetryConfiguration<TResult> Interval(TimeSpan interval)
    {
        return new FunctionRetryConfiguration<TResult>(_function, _times, interval, _condition);
    }

    public IRetryConfiguration<TResult> Until(Func<TResult, bool> condition)
    {
        return new FunctionRetryConfiguration<TResult>(_function, _times, _interval, condition);
    }
}

最后,Retry静态类,入口点:

public static class Retry
{
    public static IRetryConfiguration Do(Action action)
    {
        return new ActionRetryConfiguration(action, 1, null);
    }

    public static IRetryConfiguration<TResult> Do<TResult>(Func<TResult> action)
    {
        return new FunctionRetryConfiguration<TResult>(action, 1, null, null);
    }
}

我认为这种方法不那么多,而且更清洁。

此外,它允许你做这样的事情:

int result = Retry.Do(SomeIntMethod).Interval(TimeSpan.FromSeconds(1)).Until(n => n > 20).Execute();

Retry.Do(SomeVoidMethod).Times(4).Execute();

答案 1 :(得分:1)

微软的Reactive Framework(NuGet“Rx-Main”)已经构建了所有已经开发的运营商来开箱即用。

试试这个:

IObservable<int> query =
    Observable
        .Defer(() =>
            Observable.Start(() => GetSomeValue()))
        .Where(x => x == 1)
        .Timeout(TimeSpan.FromSeconds(0.1))
        .Retry()
        .Take(1);

query
    .Subscribe(x =>
    {
        // Can only be a `1` if produced in less than 0.1 seconds
        Console.WriteLine(x);
    });

答案 2 :(得分:0)

好吧,如果我理解了一切,这样的事情可以解决你的问题:

public static T Do<T>(Func<T> action, TimeSpan retryInterval, Predicate<T> predicate)
{
    var exceptions = new List<Exception>();
    try
    {
        bool succeeded;
        T result;
        do
        {
            result = action();
            succeeded = predicate(result);
        } while (!succeeded);

        return result;
    }
    catch (Exception ex)
    {
        exceptions.Add(ex);
    }
    throw new AggregateException(exceptions);
}

将此方法添加到您的重试类。

我已尝试使用示例ConsoleApplication,并使用以下代码:

class Program
{
    static void Main(string[] args)
    {
        var _random = new Random();

        Func<int> func = () =>
        {
            var result = _random.Next(10);
            Console.WriteLine(result);
            return result;
        };

        Retry.Do(func, TimeSpan.FromSeconds(1), i => i == 5);

        Console.ReadLine();
    }
}

事实上,它在randoms 5时会停止。

答案 3 :(得分:-1)

好像你在想这个:

int returnValue = -1;
while (returnValue != 3)
{
    returnValue = DoStuff();
    // DoStuff should include a step to avoid maxing out cpu
}
return returnValue;

当然,&#34; 3&#34;可以是传递给函数的变量。