Search code examples
c#multithreadingcircuit-breaker

How to make async call to DotNetCircuitBreaker


I'm using the DotNetCircuitBreaker and tries to call a async metod like this

private async void button1_Click(object sender, EventArgs e)
{
  var circuitBreaker = new CircuitBreaker.Net.CircuitBreaker(
    TaskScheduler.Default,
    maxFailures: 3,
    invocationTimeout: TimeSpan.FromMilliseconds(100),
    circuitResetTimeout: TimeSpan.FromMilliseconds(10000));

  //This line gets the error... Definition looks like this
  //async Task<T> ExecuteAsync<T>(Func<Task<T>> func)      
  var result = await circuitBreaker.ExecuteAsync(Calc(4, 4));
}

private async Task<int> Calc(int a, int b)
{
  //Simulate external api that get stuck in some way and not throw a timeout exception
  Task<int> calc = Task<int>.Factory.StartNew(() =>
  {
    int s;
    s = a + b;
    Random gen = new Random();
    bool result = gen.Next(100) < 50 ? true : false;
    if (result) Thread.Sleep(5000);
    return s;
  });

  if (await Task.WhenAny(calc, Task.Delay(1000)) == calc)
  {
    return calc.Result;
  }
  else
  {
    throw new TimeoutException();
  }
}

Argument 1: cannot convert from System.Threading.Tasks.Task"int" to System.Func"System.Threading.Tasks.Task"

How fix my calc method work with a


Solution

  • It looks like CircuitBreaker.ExecuteAsync expects a parameter with type Func<Task<T>>. What you supplied is a Task<T>.

    To fix it you can use a lambda expression like

    var result = await circuitBreaker.ExecuteAsync(() => Calc(4, 4));