जब भी कोई विफल ऑपरेशन होता है, तो पुन:प्रयास तर्क लागू किया जाता है। रिट्रीलॉजिक को केवल वहीं लागू करें जहां विफल ऑपरेशन का पूरा संदर्भ हो।
सभी कनेक्टिविटी विफलताओं को लॉग करना महत्वपूर्ण है जो पुन:प्रयास का कारण बनती हैं ताकि एप्लिकेशन, सेवाओं या संसाधनों के साथ अंतर्निहित समस्याओं की पहचान की जा सके।
उदाहरण
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);
}
}