如何在 C# 中编写重试逻辑?
当操作失败时会执行重试逻辑。仅在失败操作的完整上下文中实现重试逻辑。
记录导致重试的所有连接故障非常重要,以便可以发现应用程序、服务或资源的潜在问题。
示例
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);
}
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP