[英]C# Polly WaitAndRetry policy for function retry
我对 C# 编码很陌生,我只想知道如果失败,如何为我的函数设置 polly WaitAndRetry。 以下是我的步骤
我安装了包 Install-Package Polly,使用 NuGet 包
在我的代码中使用 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 和重试选项
你说你想要 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!");
}
}
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.