免费的AOP框架进行C#重试方法拦截

时间:2019-01-31 22:31:54

标签: c# aop

我对C#中的AOP完全陌生。目前,我有兴趣为使用该技术的方法编写重试。

因此,根据发布后的评论:https://doc.postsharp.net/method-interception 我已经编写了这段代码:

[Serializable]
    public class RetryAspect : MethodInterceptionAspect
{
    private int _sleep;
    private int _retries;
    private object _expectedResult;
    private object _defaultReturnValue;

    public RetryAspect(object expectedResult, int waitBetweenCycles, int numberOfRetries) : this(expectedResult, waitBetweenCycles, numberOfRetries, null) { }

    public RetryAspect(object expectedResult, int waitBetweenCycles, int numberOfRetries, object defaultReturnValue)
    {
        _expectedResult = expectedResult;
        _sleep = waitBetweenCycles;
        _retries = numberOfRetries;
        _defaultReturnValue = defaultReturnValue;
    }

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        int waitCount = 0;

        while (!args.ReturnValue.Equals(_expectedResult))
        {
            args.Proceed();

            if (waitCount++ < _retries)
            {
                Thread.Sleep(_sleep);
            }
            else
            {
                if (_defaultReturnValue != null)
                {
                    args.ReturnValue = _defaultReturnValue;
                }

                break;
            }
        }
    }
}

class Program
{
    static int cnt = 0;

    static void Main(string[] args)
    {
        Console.WriteLine(Test());
        Console.ReadKey();
    }

    [RetryAspect(true, 1000, 5)]
    public static bool Test()
    {
            Console.WriteLine("Test {0}", cnt);
            if (cnt == 4)
            {
                return true;
            }
            else
            {
                cnt++;
                return false;
            }
    }
}

现在,有没有一种方法可以通过使用自由/开源AOP框架来达到相同的结果?到目前为止,我还没有找到使用其他AOP框架的有用示例。

1 个答案:

答案 0 :(得分:0)

虽然不是AOP,但我建议您使用Polly

  

Polly是一个.NET弹性和瞬态故障处理库,允许开发人员表达诸如Retry等策略。

您只需要使用其流畅的API来定义您的政策:

var policy = Policy
              .HandleResult<bool>(false)
              //Or using one of WaitAndRetry overloads if you want to sleep between retries 
              .Retry(5);

并执行它:

policy.Execute(() => Test());
相关问题