利用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();