只要操作失败,就会执行重试逻辑。仅在失败操作的整个上下文中才实施重试逻辑。
记录导致重试的所有连接失败很重要,这样才能识别应用程序,服务或资源的潜在问题。
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); } }