问题描述
我对C#编码非常陌生,我只想知道如何在函数失败时为我的函数设置polly WaitAndRetry。以下是我的步骤
-
我使用NuGet软件包安装了软件包Install-Package Polly
-
下面是我的代码
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; }
但是此呼叫正在连续呼叫,没有任何延迟。我试图在catch调用中使用WaitAndRetryAsync,但是它不起作用。WaitAndRetryAsync仅接受HTTP Repose消息。我想在try-catch中实现ait and retry选项
解决方法
您说您想要WaitAndRetry,但是您不使用该功能...而且它不仅与HttpResponse一起使用。请阅读documentation。
下面的代码应为您提供一个良好的开端:
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!");
}
}