只要操作失败,就会实现重试逻辑。实施重试 仅在失败操作的完整上下文中记录逻辑。
记录导致重试的所有连接故障非常重要,以便底层 可以识别应用程序、服务或资源的问题。
示例
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); } }
登录后复制