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