Search code examples
c#.netxamarinpolly

Polly continue after X retries


I'm using Polly in a Xamarin project which works pretty great. The problem I'm facing is that after 2 retries it should continue the method, but for some reason it gets stuck and keeps retrying. Does anyone know how I can do this?

private async Task<List<EventDto>> GetEventsErrorRemoteAsync()
{
    List<EventDto> conferences = null;

    if (CrossConnectivity.Current.IsConnected) 
    {
        // Retrying a specific amount of times (5)
        // In this case will wait for
        //  1 ^ 2 = 2 seconds then
        //  2 ^ 2 = 4 seconds then
        //  3 ^ 2 = 8 seconds then
        //  4 ^ 2 = 16 seconds then
        //  5 ^ 2 = 32 seconds
        conferences = await Policy
            .Handle<Exception>()
            .WaitAndRetryAsync(
                retryCount: 2, 
                sleepDurationProvider:retryAttempt => 
                    TimeSpan.FromSeconds(Math.Pow (2, retryAttempt)), 
                onRetry: (exception, timeSpan, context) => 
                {
                    var ex = (ApiException)exception;

                    //Do something with exception. Send to insights (now hockeyapp)
                    Debug.WriteLine($"Error: {ex.ReasonPhrase} | 
                        TimeSpan: {timeSpan.Seconds}");
                    return;
                }).ExecuteAsync(async () => 
                    await _eventService.GetEventsWithError());
    }
    return conferences;
}

Solution

  • Question answered in detail on the identical Github issue: https://github.com/App-vNext/Polly/issues/106

    The Policy is not stuck keeping retrying. Rather, if the final attempt made by the retry policy at executing the delegate within .ExecuteAsync() still throws, the retry policy will rethrow this final exception. As you are not catching and handling that exception, the method is naturally not continuing to the return statement.