只要操作失敗,就會(huì)實(shí)現(xiàn)重試邏輯。實(shí)施重試
僅在失敗操作的完整上下文中記錄邏輯。
記錄導(dǎo)致重試的所有連接故障非常重要,以便底層
可以識(shí)別應(yīng)用程序、服務(wù)或資源的問題。
示例
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); } }
登錄后復(fù)制
以上就是如何用C#編寫重試邏輯?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.xfxf.net其它相關(guān)文章!