The following code is a linqpad program.
- The
payloadListcontains json-objects like{"id": 1, "foo": "one" }. - Each object of
payloadListshould be sent to a server withhttpClient.SendAsync() - The
responsefor each request should be stored inresponseList
The code below does partly work. But i do not understand why some parts are not working. I assume that the responses are not completed when responseList.Add(foo) is executed.
This request shall be send for each json-object {"id": 1, "foo": "one" }
public static async Task<string> DoRequest(HttpClient client, string payload) { var request = new HttpRequestMessage(HttpMethod.Post, "http://httpbin.org/anything"); request.Content = new StringContent(payload , Encoding.UTF8, "application/json"); var response = await client.SendAsync(request); string responseContent = await response.Content.ReadAsStringAsync(); return responseContent; } The DoRequest()-method wraps the request and can be used inside main like this
static async Task Main() { var responseList = new List<string>(); var payloadList = new List<string>{"{ 'id': 1, 'bar': 'One'}", "{ 'id': 2, 'bar': 'Two'}", "{ 'id': 3, 'bar': 'Three'}"}; var client = new HttpClient(); payloadList.ForEach(async (payload) => { var responseFoo = await DoRequest(client, payload); responseFoo.Dump("response"); // contains responseFoo responseList.Add(responseFoo); // adding responseFoo to list fails }); responseList.Dump(); // is empty } The responseList is empty.
- Expected
responseList.Dump()contains all responsesresponseFoo. - Actual
responseListis empty.
Questions
- How can each response for
await client.SendAsync(request)be added to a responseList? - Why is
responseListempty despite thatfoo.Dump()works? - How to confirm or check if every
client.SendAsyncis finished? - Would you write the code above different - why?

responseList.Add(foo); // this not...in what way does it "not work"? Is there an error?responseList.Dump()contains all responsesfoo. ActualresponseListis empty.responseList.Dump();outside the foreach loop obviously won't work because that'll run before all the async stuff is complete.