I'm very new to C# coding and I just want to know how to setup polly WaitAndRetry for my function if it failed. Following is my steps
I installed package Install-Package Polly, using NuGet package
added using polly in my code.
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. I want to implement ait and retry option in try-catch
You say you want WaitAndRetry but you don't use that function... And it doesn't only work with 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());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.