
只要操作失败,就会实现重试逻辑。实施重试 仅在失败操作的完整上下文中记录逻辑。
记录导致重试的所有连接故障非常重要,以便底层 可以识别应用程序、服务或资源的问题。
class Program{
public static void Main(){
HttpClient client = new HttpClient();
dynamic res = null;
var retryAttempts = 3;
var delay = TimeSpan.FromSeconds(2);
RetryHelper.Retry(retryAttempts, delay, () =>{
res = client.GetAsync("https://example22.com/api/cycles/1");
});
Console.ReadLine();
}
}
public static class RetryHelper{
public static void Retry(int times, TimeSpan delay, Action operation){
var attempts = 0;
do{
try{
attempts++;
System.Console.WriteLine(attempts);
operation();
break;
}
catch (Exception ex){
if (attempts == times)
throw;
Task.Delay(delay).Wait();
}
} while (true);
}
}以上就是如何用C#编写重试逻辑?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号