c# 中Exception 的重试机制

有时候我们在项目中碰到,比如这样那样的原因(网络或者是其他的原因)导致方法调用失败,大部分的方法是在触发一次方法调用,其实我们可以通过自定义Exception,然后提供调用的方法名称和参数等等,提供一种自动的重试多次的机制。

其实方法是很简单的,我们先自定义一个Exception

代码如下



 public class RetryException : Exception
    {
        private int RetryTimes;
        private string MethodName;
        private object[] Values;
        private Type ClassType;
        public RetryException(int retryTimes, Type classType, string method, params object[] values)
        {
            RetryTimes = retryTimes;
            MethodName = method;
            Values = values;
            ClassType = classType;
            RetryMethod();
        }
        public RetryException(string message, int retryTimes, Type classType, string method, params object[] values)
            : base(message)
        {
            RetryTimes = retryTimes;
            MethodName = method;
            ClassType = classType;
            Values = values;
            RetryMethod();
        }
        public RetryException(string message, Exception innerException, int retryTimes, Type classType, string method, params object[] values)
            : base(message, innerException)
        {
            RetryTimes = retryTimes;
            MethodName = method;
            ClassType = classType;
            Values = values;
            RetryMethod();
        }
        private void RetryMethod()
        {
            if (string.IsNullOrEmpty(MethodName))
                throw new Exception("method 为空");
            if (RetryTimes == 0)
                throw new Exception("重试次数为空");
            if (ClassType == null)
                throw new Exception("ClassType为空");
            object instance = Activator.CreateInstance(ClassType);
            MethodInfo Method = ClassType.GetMethod(MethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
            do
            {
                try
                {   
                    Method.Invoke(instance, Values);
                }
                catch (Exception ex)
                {
                    if (RetryTimes > 1)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                    else
                    {
                        throw ex;
                    }
                }
                RetryTimes--;
            } while (RetryTimes > 0);
        }
    }

使用方法 我们先定义一个简单的方法如下

 public class service
    {
        public void GetName(string message,object obj)
        {
            if (message == "error")
                throw new Exception(" message");
               
        }
    }

调用的方法是

  service sv = new service();
            object obj = new object();
            try
            {
                sv.GetName("error",obj);
            }
            catch (Exception ex)
            {
               new RetryException(5, typeof(service), "GetName", new object[] {"error",obj});
            }

posted @ 2011-05-23 11:38  留云  阅读(1037)  评论(2编辑  收藏  举报