In software development, some operations may need to be tried multiple times to successfully complete. Traditional methods usually use the
cycle with explicit retry times, such as the following code:
while
<code class="language-csharp">int retries = 3; while (true) { try { DoSomething(); break; // 成功! } catch { if (--retries == 0) throw; else Thread.Sleep(1000); } }</code>
Introduce
Class
Retry
The goal is to create a reusable class, which accepts a commission as a parameter and performs operations in the re -test block. The following code provides a possible implementation:
Retry
Use
<code class="language-csharp">public static class Retry { public static void Do(Action action, TimeSpan retryInterval, int maxAttemptCount = 3) { Do(() => { action(); return null; }, retryInterval, maxAttemptCount); } public static T Do<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3) { var exceptions = new List<Exception>(); for (int attempted = 0; attempted < maxAttemptCount; attempted++) { try { return action(); } catch (Exception ex) { exceptions.Add(ex); if (attempted < maxAttemptCount -1) { Thread.Sleep(retryInterval); } } } throw new AggregateException(exceptions); } }</code>
This method can be used in various ways to achieve retry logic: Retry
The above is the detailed content of How to Elegantly Implement Retry Logic in C#?. For more information, please follow other related articles on the PHP Chinese website!