Home > Backend Development > C++ > How Can Lambda Expressions Simplify Retry Logic in C#?

How Can Lambda Expressions Simplify Retry Logic in C#?

Barbara Streisand
Release: 2025-01-29 08:51:09
Original
729 people have browsed it

How Can Lambda Expressions Simplify Retry Logic in C#?

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

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

For methods returning a value:

<code class="language-csharp">int result = RetryHelper.Execute(() => SomeMethodReturningInt(), TimeSpan.FromMilliseconds(500), 5);</code>
Copy after login

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!

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