Home > Backend Development > C++ > How Can C# Lambda Expressions Cleanly Implement Retry Logic for Handling Potential Failures?

How Can C# Lambda Expressions Cleanly Implement Retry Logic for Handling Potential Failures?

Barbara Streisand
Release: 2025-01-29 08:46:13
Original
178 people have browsed it

How Can C# Lambda Expressions Cleanly Implement Retry Logic for Handling Potential Failures?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template