I want to process async results as they finish but these async results are nested two layers deep. For instance, take this block of code:
var responseTaskList = new List<Task<HttpResponseMessage>>();
for (var i = 0; i < 10; i++)
responseTaskList.Add(httpClient.GetAsync(uri));
while (responseTaskList.Any())
{
var responseTask = await Task.WhenAny(responseTaskList);
responseTaskList.Remove(responseTask);
//Do Something with responseTask.Result
}
We're creating a list of tasks and when any return we do something.
I want to basically continue and do something when each continuation finishes.
I want to do this for response.Content
So something like this:
var contentTaskList = new List<Task<Task<string>>>();
for (var i = 0; i < 10; i++)
contentTaskList.Add(httpClient.GetAsync(uri)
.ContinueWith(rt => rt.Result.Content.ReadAsStringAsync()));
while (contentTaskList.Any())
{
var contentTaskTask = await Task.WhenAny(contentTaskList);
contentTaskList.Remove(contentTaskTask);
context.WriteLine(contentTaskTask.Result.Result);
}
Is this the best way to write this code and will this effectively write a line to the context as soon as each response returns and reads its content?