简体   繁体   English

C# Polly WaitAndRetry 函数重试策略

[英]C# Polly WaitAndRetry policy for function retry

I'm very new to C# coding and I just want to know how to setup polly WaitAndRetry for my function if it failed.我对 C# 编码很陌生,我只想知道如果失败,如何为我的函数设置 polly WaitAndRetry。 Following is my steps以下是我的步骤

  1. I installed package Install-Package Polly, using NuGet package我安装了包 Install-Package Polly,使用 NuGet 包

  2. added using polly in my code.在我的代码中使用 polly添加。

  3. Below is my code下面是我的代码

    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<strig> SendToDataBase(config model) { var ss = DataBase.PostCallAsync(model).GetAwaiter().GetResult(); return ss; }

But this call is continuously calling without any delay.但是这个电话是没有任何延迟地不断地呼唤着。 I tried to use WaitAndRetryAsync in catch call but it's not working.WaitAndRetryAsync accepts only HTTP repose message.我尝试在 catch 调用中使用 WaitAndRetryAsync,但它不起作用。WaitAndRetryAsync 只接受 HTTP repose 消息。 I want to implement ait and retry option in try-catch我想在 try-catch 中实现 ait 和重试选项

You say you want WaitAndRetry but you don't use that function... And it doesn't only work with HttpResponse.你说你想要 WaitAndRetry 但你不使用那个函数......而且它不仅适用于 HttpResponse。 Please read the documentation .请阅读文档

The code below should give you a head start:下面的代码应该给你一个良好的开端:

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!");
    }
}
class Program
{
    static 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>()
          .WaitAndRetry(new[]
          {
            TimeSpan.FromSeconds(1),
            TimeSpan.FromSeconds(2),
            TimeSpan.FromSeconds(3)
          });

        // execute the policy
         policy.Execute(() =>  SendToDatabase());

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM