Retry parallel API call if fail

Viewed 476

I've used the below code from this post - What is the best way to cal API calls in parallel in .net Core, C#?

It works fine, but when I'm processing a large list, some of the calls fail.

My question is, how can I implement Retry logic into this?

 foreach (var post in list)
        {
            async Task<string> func()
            {
                var response = await client.GetAsync("posts/" + post);
                return await response.Content.ReadAsStringAsync();
            }

            tasks.Add(func());
        }

        await Task.WhenAll(tasks);

        var postResponses = new List<string>();

        foreach (var t in tasks) {
            var postResponse = await t; //t.Result would be okay too.
            postResponses.Add(postResponse);
            Console.WriteLine(postResponse);
        }

This is my attempt to use Polly. It doesn't work as it still fails on around the same amount of requests as before.

What am I doing wrong?

var policy = Policy
              .Handle<HttpRequestException>()
              .RetryAsync(3);

foreach (var mediaItem in uploadedMedia)
{
    var mediaRequest = new HttpRequestMessage { *** }
    async Task<string> func()
    {
        var response = await client.SendAsync(mediaRequest);
        return await response.Content.ReadAsStringAsync();                            
    }                      
    tasks.Add(policy.ExecuteAsync(() => func()));                                              
}                                          
await Task.WhenAll(tasks);
0 Answers
Related