C# Polly WaitAndRetry 函数重试策略

jun*_*lex 1 c# async-await polly retry-logic

我对 C# 编码非常陌生,我只想知道如果函数失败,如何为我的函数设置 polly WaitAndRetry。以下是我的步骤

  1. 我使用 NuGet 包安装了 Install-Package Polly 包
  2. 在我的代码中添加使用 polly 。
  3. 下面是我的代码
public async Task<string> ConfigInsert(config model)
{
    try
    {
        SendToDatabase(model);

        await Policy.Handle<Exception>()
            .RetryAsync(NUMBER_OF_RETRIES)
            .ExecuteAsync(async () =>
                await SendToDatabase(model))
            .ConfigureAwait(false);
    } 
    Catch(Exception e)
    {
        _log.write("error occurred");
    }
        
    public async Task<string> SendToDataBase(config model)
    {
        var ss = DataBase.PostCallAsync(model)
            .GetAwaiter()
            .GetResult();
        return ss;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这通电话却是连续不断地呼叫着,没有任何的延迟。我尝试在 catch 调用中使用 WaitAndRetryAsync 但它不起作用。WaitAndRetryAsync 仅接受 HTTP 休息消息。我想在 try-catch 中实现 ait 和重试选项

jer*_*enh 6

你说你想要 WaitAndRetry 但你不使用这个函数......而且它不仅仅适用于 HttpResponse。请阅读文档

下面的代码应该可以让您抢占先机:

class Program
{
    static async Task Main(string[] args)
    {
        // define the policy using WaitAndRetry (try 3 times, waiting an increasing numer of seconds if exception is thrown)
        var policy = Policy
          .Handle<Exception>()
          .WaitAndRetryAsync(new[]
          {
            TimeSpan.FromSeconds(1),
            TimeSpan.FromSeconds(2),
            TimeSpan.FromSeconds(3)
          });

        // execute the policy
        await policy.ExecuteAsync(async () => await SendToDatabase());

    }

    static async Task SendToDatabase()
    {
        Console.WriteLine("trying to send to database");
        await Task.Delay(100);
        throw new Exception("it failed!");
    }
}
Run Code Online (Sandbox Code Playgroud)