I'm trying to understand how Polly Fallback works, but I'm not getting the implementation right.
As I understand it, it performs another action if the first fails, but that is not what is happening.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CircuitBreakingPolly
{
public class Program
{
public static int n1 = 2;
public static int n2 = 0;
public static DateTime programStartTime;
private static List<Produtos> produtos = new List<Produtos>();
static void Main(string[] args)
{
var pmp = new PoliticasManipulacaoPolly();
Task result = pmp.ExecuteFallback(() => CallTask(), () => CallTask2());
Console.WriteLine(result.ToString());
Console.ReadKey();
}
public async static Task CallTask()
{
if (DateTime.Now < programStartTime.AddSeconds(10))
{
Console.WriteLine("Task falhou.");
throw new TimeoutException();
}
await Task.Delay(TimeSpan.FromSeconds(1));
Console.WriteLine("Task completa.");
}
public async static Task CallTask2()
{
if (DateTime.Now < programStartTime.AddSeconds(10))
{
Console.WriteLine("Task falhou.");
throw new TimeoutException();
}
await Task.Delay(TimeSpan.FromSeconds(1));
Console.WriteLine("Task completa.");
}
}
}
My method;
public Task ExecuteFallback(Func<Task> action, Func<Task> fallbackAction)
{
Program.programStartTime = DateTime.Now;
Task result = null;
try
{
var esult2 = Policy.Handle<Exception>()
.Fallback(() => fallbackAction(), onFallback: (exception, context) =>
{
Console.WriteLine(exception.Message);
//Log(exception);
throw exception;
})
.Execute(action);
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
//Log(ex);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//Log(ex);
}
return result;
}
In the call of my first method this is simulating correctly, but the second method is not called after the first error.