Goal:
Show the message "show error" after 3 attempt.
Problem:
What part of the code do not work in order to achieve the goal.
using Polly;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsolePollyTest2
{
class Program
{
static void Main(string[] args)
{
var maxRetryAttempts = 3;
var pauseBetweenFailures = TimeSpan.FromSeconds(2);
Policy
.Handle<HttpRequestException>()
.Or<TaskCanceledException>()
.WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures)
.ExecuteAsync(PersistApplicationData2)
.ContinueWith(x =>
{
if (x.Exception != null)
{
Console.WriteLine("show error");
}
});
}
private static async Task PersistApplicationData2()
{
int ddfd = 3;
var df = ddfd / 0;
Console.WriteLine("Show data");
await Task.FromResult<object>(null);
}
}
}
Thank you!
Await your task to be run first also your policy says in case of HttpRequestException
or TaskCanceledException
retry policy will work and your method has no any exception of those.
If you want to test retry policy you can do some thing like this:
public static async Task Main(string[] args)
{
var maxRetryAttempts = 3;
var pauseBetweenFailures = TimeSpan.FromSeconds(2);
await Policy
.Handle<HttpRequestException>()
.Or<Exception>() //if any exception raised will try agian
.Or<TaskCanceledException>()
.WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures)
.ExecuteAsync( PersistApplicationData2)
.ContinueWith(x =>
{
if (x.Exception != null)
{
Console.WriteLine("show error");
}
//success
}, scheduler: TaskScheduler.Default);
}