Streamlining Retry Logic with C# Lambda Expressions
Robust applications often require retry mechanisms to handle potential failures gracefully. While traditional retry loops can be complex and prone to errors, C# lambda expressions offer a more elegant and reusable solution.
This article demonstrates a Retry
class that simplifies retry logic. The core functionality is encapsulated in the Do
method, which accepts a lambda expression representing the operation to be retried.
Here's a generalized implementation:
<code class="language-csharp">public static class Retry { public static void Do(Action action, TimeSpan retryInterval, int maxAttemptCount = 3) { var exceptions = new List<Exception>(); for (int attempted = 0; attempted < maxAttemptCount; attempted++) { try { action(); break; // Success! Exit the loop. } catch (Exception ex) { exceptions.Add(ex); if (attempted < maxAttemptCount - 1) { Thread.Sleep(retryInterval); } } } if (exceptions.Any()) { throw new AggregateException(exceptions); } } }</code>
This Do
method allows for flexible retry configurations: specifying the retry interval and the maximum number of attempts. It collects any exceptions encountered and throws an AggregateException
if all attempts fail.
Using the Retry
class is simple and intuitive:
<code class="language-csharp">Retry.Do(() => SomeFunctionThatMightFail(), TimeSpan.FromSeconds(1));</code>
This approach provides a cleaner, more maintainable, and reusable way to implement retry logic in C#, leveraging the power and conciseness of lambda expressions for a more efficient and robust error-handling strategy.
The above is the detailed content of How Can C# Lambda Expressions Cleanly Implement Retry Logic for Handling Potential Failures?. For more information, please follow other related articles on the PHP Chinese website!