4
I’m trying to understand how it works Fallback by Polly, but I’m not getting the implementation right.
From what I understand he executes another action if the first fails, but that’s 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 simulating correctly, but is not called the second method after the error of the first.