My string is empty when all the work is completed. Any solution for that?
string jsonString = "";
List<Task> tasksToWait = new List<Task>();
// ...
foreach (string blah in blahs)
{
counter++;
// ...
Task task = new Task(async () =>
{
HttpResponseMessage response = await client.GetAsync(baseURL + URLparams);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
jsonString += responseBody + ",";
});
task.Start();
tasksToWait.Add(task);
if (counter == 50)
{
Task.WaitAll(tasksToWait.ToArray());
tasksToWait.Clear();
Console.WriteLine(jsonString);
}
// ...
}
In an effort to speed things up, I am kicking off multiple API requests at once rather than wait for one at a time. Open to other options/solutions.
Thanks!
new Taskat all, givenHttpClientis already async?Taskconstructor with an async lambda you end up with an async void lambda that can't be awaited. To fix this problem you must either use aTask<Task>constructor, or preferably the handyTask.Run. Look here for a more thorough explanation.