I'm using HttpClient to asynchronously make many requests to an external api. I wait for all the requests to complete, then use the responses in other code. My problem is that if I make too many requests, my code throws an exception when I use the Task.WhenAll to wait.
This code will ultimately be run in parallel, by which I mean that I'll be doing many sets of these async requests at the same time (i.e. 10 sets of 200 async requests). I've instantiated an HttpClient that I'm using with .NET 4.5 async/await modifiers like this:
using (var client = new HttpClient())
{
// make a list of tasks
List<Task<HttpResponseMessage>> taskList;
List<MyData> replies;
for (int i = 0; i < MAX_NUMBER_REQUESTS; i++)
{
taskList.Add(client.GetAsync(externalUri);
}
List<HttpResponseMessage> responses = await Task.WhenAll(taskList);
// read each response after they have returned
foreach (var response in responses)
{
var reader = new System.IO.StreamReader(await response.Content.ReadAsStreamAsync());
replies.Add(JsonConvert.DeserializeObject<MyData>(reader.ReadToEnd()));
reader.Close();
}
foreach (var reply in replies)
{
// do something with the response from the external api call...
}
}
I keep getting a TaskCanceledException. After looking into this I saw this is possibly a timeout issue. I have no idea how to fix it. I attempted to batch my requests at 100 requests before using the Task.WhenAll and repeating, which worked. Then when I ran that in parallel with three sets of 100 requests that fails. Am I missing something, does anyone have any insight into this?