Streamlining C# Retry Logic with Lambda Expressions
In C#, retrying operations is a common task. Traditional methods often involve explicit retry loops, leading to verbose and less reusable code. Lambda expressions offer a more elegant solution.
This example demonstrates a reusable lambda-based retry wrapper:
<code class="language-csharp">public static class RetryHelper { public static void Execute(Action action, TimeSpan retryInterval, int maxAttempts = 3) { Execute(() => { action(); return null; }, retryInterval, maxAttempts); } public static T Execute<T>(Func<T> action, TimeSpan retryInterval, int maxAttempts = 3) { var exceptions = new List<Exception>(); for (int attempt = 0; attempt < maxAttempts; attempt++) { try { return action(); } catch (Exception ex) { exceptions.Add(ex); if (attempt < maxAttempts - 1) { Thread.Sleep(retryInterval); } } } throw new AggregateException("Retry attempts failed.", exceptions); } }</code>
This RetryHelper
class encapsulates retry logic. You provide the action (or function) to retry, the retry interval, and the maximum number of attempts.
Usage is straightforward:
<code class="language-csharp">RetryHelper.Execute(() => SomeMethodThatMightFail(), TimeSpan.FromSeconds(2)); </code>
For methods returning a value:
<code class="language-csharp">int result = RetryHelper.Execute(() => SomeMethodReturningInt(), TimeSpan.FromMilliseconds(500), 5);</code>
An asynchronous overload could easily be added for asynchronous operations. This approach provides a concise and reusable solution for handling retry logic in C#.
The above is the detailed content of How Can Lambda Expressions Simplify Retry Logic in C#?. For more information, please follow other related articles on the PHP Chinese website!