Home > Backend Development > C++ > How to Elegantly Implement Retry Logic in C#?

How to Elegantly Implement Retry Logic in C#?

DDD
Release: 2025-01-29 08:32:11
Original
391 people have browsed it

How to Elegantly Implement Retry Logic in C#?

Realize the logic of retrying the logic elegantly in C#

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

Although this method ensures that the operation will be repeatedly defined, the compilation may be complicated in different cases. More common methods can provide more concise and reusable solutions.
<code class="language-csharp">int retries = 3;
while (true)
{
    try
    {
        DoSomething();
        break; // 成功!
    }
    catch
    {
        if (--retries == 0) throw;
        else Thread.Sleep(1000);
    }
}</code>
Copy after login

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

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

This method can be used in various ways to achieve retry logic: Retry

As shown, this method provides a flexible way to handle retry, which can specify the number of attempts, retry interval, and operation to be executed.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template