Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Polly for a retry attempt from an async function

I'm trying to retry a failed operation 3 times.

I'm using Polly for a retry operation.

I want to get the exception in case the retry operation fails and retry again 2 times and so on.

return await Policy
           .Handle<CustomException>()
           .RetryAsync(3, onRetryAsync: async (exception, retryCount, context) =>
           {
               return await runner.run(params);
           });

The function should return

Task<IReadOnlyCollection<string>>

I'm getting the following error:

async lambda expression converted to a task returning delegate cannot return a value

like image 332
Ace Avatar asked Dec 23 '19 13:12

Ace


People also ask

How does Polly retry work?

With Polly, you can define a Retry policy with the number of retries, the exponential backoff configuration, and the actions to take when there's an HTTP exception, such as logging the error. In this case, the policy is configured to try six times with an exponential retry, starting at two seconds.

What is Polly in C #?

Polly is a . NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, Rate-limiting and Fallback in a fluent and thread-safe manner.


1 Answers

I think it is unusual to run your logic in the retry policy - unless I misunderstand your question. More typically you execute the policy by calling a method that runs your logic.

Something like this:

async Task Main()
{
    var polly = Policy
           .Handle<Exception>()        
           .RetryAsync(3, (exception, retryCount, context) => Console.WriteLine($"try: {retryCount}, Exception: {exception.Message}"));

    var result = await polly.ExecuteAsync(async () => await DoSomething());
    Console.WriteLine(result);
}

int count = 0;

public async Task<string> DoSomething()
{
    if (count < 3)
    {
        count++;
        throw new Exception("boom");
    }

    return await Task.FromResult("foo");
}

output

try: 1, Exception: boom
try: 2, Exception: boom
try: 3, Exception: boom
foo
like image 174
Crowcoder Avatar answered Nov 10 '22 09:11

Crowcoder