如何让一段代码重复运行N次(出错时)

public delegate void AnonymousHandler();

/// <summary>
/// 重试某过程 maxError 次,直到成功或失败
/// </summary>
/// <param name="handler">托管函数</param>
/// <param name="maxError">允许失败的次数</param>
/// <returns>如果执行成功,则返回 null, 否则返回该错误对象</returns>
public static Exception Trys(AnonymousHandler handler, int maxError) {
if (handler != null) {
Exception ex = null;
for (int a = 0; a < maxError; a++) {
try {
handler();
return null;
} catch (Exception e) {
ex = e;
}
}
return ex;
}
return null;
}

ex = Lib.Trys(delegate()
{
ie.Action = url;
ie.CookieContainer = new CookieContainer();
ie.AcceptLanguage = "zh-cn,zh;q=0.5";
ie.CookieContainer.SetCookies(ie.Address, "Culture=zh-hk");
ie.Send();
Thread.CurrentThread.Join(100);
}, 10);

原文地址:https://www.cnblogs.com/yufan27209/p/4121935.html