以下代码是一个 linqpad 程序。
payloadList
包含像{"id": 1, "foo": "one" }
这样的 json 对象。- 每个
payloadList
的对象都应该使用httpClient.SendAsync()
发送到服务器。 - 每个请求的
response
应该存储在responseList
中。
下面的代码部分工作。但我不明白为什么有些部分不起作用。我猜测当执行 responseList.Add(foo)
时,响应还没有完成。
对于每个 json 对象 {"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;
}
DoRequest()
方法封装了请求,可以在主函数内像这样使用
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
}
responseList为空。
- 预期
responseList.Dump()
包含所有的响应responseFoo
。 - 实际上
responseList
是空的。
问题
- 如何将每个
await client.SendAsync(request)
的响应添加到responseList中? - 为什么
responseList
为空,尽管foo.Dump()
有效? - 如何确认或检查每个
client.SendAsync
是否已完成? - 您会以不同的方式编写上面的代码吗?为什么?
responseList.Dump()
包含所有响应foo
。实际上,responseList
为空。 - surfmuggleresponseList.Dump();
放在 foreach 循环外显然行不通,因为它会在所有异步操作完成之前运行。 - ADyson