1

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?

lanierhall
  • 530
  • 1
  • 5
  • 15
  • 1
    There are *very* few situations in which it makes sense to use `ContinueWith`. You should almost always be using *await* to add continuations to async operations. If you re-write your code to use `async` methods, rather than `ContinueWith`, you'll find that you don't end up with nested tasks that you have to worry about. You could write the `ContinueWIth` code to fix that, but you'd still have numerous other things to have to fix that `await` already handles for you. – Servy Feb 28 '18 at 22:22
  • Note that rather than your approach for handling tasks as they complete I'd suggest [using a method to order the tasks by their completion time](https://stackoverflow.com/questions/36776546/waiting-for-a-single-task-to-fail-out-of-a-listtask-more-cleanly-possibly/36776706#36776706), as that will come out a lot nicer. – Servy Feb 28 '18 at 22:29

0 Answers0