zoukankan      html  css  js  c++  java
  • 利用Func封装“方法重试”功能

    利用Func封装“方法重试”功能

      忙余,写个利用Func封装方法重试的功能。该方法主要实现带有返回参数的方法实现多次重试,只要返回的结果不是所限定的返回值,则自动重试X次。Talk is cheap. Show me the code.

    /// <summary>
    /// 执行重试方法
    /// </summary>
    /// <param name="func">要执行的方法.</param>
    /// <param name="arg1">参数1.</param>
    /// <returns> 返回bool类型,该返回类型可以自己改为T类型</returns>
     public static bool RetryFuncMain(Func<string, bool> func, string arg1)
            {
                bool retBool = false;
                for (int i = 0; i < 3; i++)
                {
                    try
                    {
                        retBool = (bool)func(arg1);
                        if (retBool)
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Default.Error("RetryFuncMain出现错误:", ex);
                        Thread.Sleep(2000);
                    }
                }
    
                return retBool;
            }
    

    要执行的方法示例

    private bool PostIdentificationMethod(string postData)
            {
                bool flag = false;
                try
                {
                    using (WebClient client = new WebClient())
                    {
                        string retString = Encoding.UTF8.GetString(client.DownloadData("http://www.baidu.com"));
                    }
                    flag = true;
                }
                catch (Exception ex)
                {
                    // this.ShowLogs(null, "出现错误:" + ex.Message);
                }
                return flag;
            }
    

    调用示例

    单线程调用示例:

    Func<string,bool> func = (a) => { return PostIdentificationMethod(a); };
    RetryFuncMain(func,"发送的字符串");
    

    多线程调用示例:

     Func<string, bool> func = (a) => { return PostIdentificationMethod(a); };
     string imgString = "{"OT":"Identification","SubjectName":"发送的字符串"}";
     Task T1 = new Task(() => RetryFuncMain(func, imgString));
     T1.Start();
    
  • 相关阅读:
    最常见VC++编译错误信息集合
    网站运营最全总结
    KdPrint/DbgPrint and UNICODE_STRING/ANSI_STRING
    poj 2155 matrix
    【hdu2955】 Robberies 01背包
    【hdu4570】Multi-bit Trie 区间DP
    2014 SCAU_ACM 暑期集训
    qpython 读入数据问题: EOF error with input / raw_input
    【转】Python version 2.7 required, which was not found in the registry
    华农正方系统 登录地址
  • 原文地址:https://www.cnblogs.com/zh672903/p/10911611.html
Copyright © 2011-2022 走看看