c#

C# Polly如何实现重试策略

小樊
91
2024-07-13 23:27:23
栏目: 编程语言

在C#中,Polly是一个专门用于处理重试策略的库,可以通过NuGet包管理器安装。以下是一个示例代码,演示如何使用Polly来实现一个简单的重试策略:

using Polly;
using System;

class Program
{
    static void Main()
    {
        var policy = Policy
            .Handle<Exception>()
            .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                (exception, timeSpan, retryCount, context) =>
                {
                    Console.WriteLine($"Retry {retryCount} due to {exception}");
                });

        policy.Execute(() =>
        {
            // 调用可能会失败的方法
            DoSomething();
        });
    }

    static void DoSomething()
    {
        Console.WriteLine("Doing something...");
        // 模拟方法失败
        throw new Exception("Something went wrong");
    }
}

在上面的示例代码中,我们首先创建了一个重试策略,使用WaitAndRetry方法指定重试次数和重试间隔。然后,在policy.Execute方法中,我们调用可能会失败的方法DoSomething(),并使用重试策略来处理可能的异常。

如果DoSomething()方法抛出异常,Polly会根据我们指定的重试策略进行重试,并在每次重试时输出相应的信息。通过这种方式,我们可以灵活地控制重试策略,提高程序的稳定性和可靠性。

0
看了该问题的人还看了