The following code is a linqpad program.
- The
payloadList
contains json-objects like{"id": 1, "foo": "one" }
. - Each object of
payloadList
should be sent to a server withhttpClient.SendAsync()
- The
response
for 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
responseList
is empty.
Questions
- How can each response for
await client.SendAsync(request)
be added to a responseList? - Why is
responseList
empty despite thatfoo.Dump()
works? - How to confirm or check if every
client.SendAsync
is finished? - Would you write the code above different - why?