ตรรกะการลองใหม่จะถูกนำมาใช้เมื่อใดก็ตามที่มีการดำเนินการที่ล้มเหลว ใช้การลองใหม่อีกครั้งในบริบททั้งหมดของการดำเนินการที่ล้มเหลวเท่านั้น
สิ่งสำคัญคือต้องบันทึกความล้มเหลวในการเชื่อมต่อทั้งหมดที่ทำให้เกิดการลองใหม่ เพื่อให้สามารถระบุปัญหาพื้นฐานกับแอปพลิเคชัน บริการ หรือทรัพยากรได้
ตัวอย่าง
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);
}
}