gpt4 book ai didi

c# - 如何使用 HttpClient() 存储来自多个异步请求的返回数据,直到所有请求完成?

转载 作者:行者123 更新时间:2023-11-30 17:40:54 26 4
gpt4 key购买 nike

我需要遍历一系列从 url 获取数据的 post 请求。请求需要是异步的。检查所有返回已完成并存储该数据直到返回所有数据的最佳方法是什么?更喜欢使用 HttpClient()

代码片段:

     HttpContent httpContent = new FormUrlEncodedContent(postData);           
HttpResponseMessage response = client.PostAsync("/mydata", httpContent).Result;

var responsecode = (int)response.StatusCode;

if (response.IsSuccessStatusCode)
{
var responseBodyAsText = await response.Content.ReadAsStringAsync();
return responseBodyAsText;
}
else
{
return responsecode +" " +response.ReasonPhrase;
}

`

最佳答案

好吧,首先,请记住这里有一个异步问题:

 HttpContent httpContent = new FormUrlEncodedContent(postData);           

// whoops! .Result makes this line synchronous.
HttpResponseMessage response = client.PostAsync("/mydata", httpContent).Result;

var responsecode = (int)response.StatusCode;

if (response.IsSuccessStatusCode)
{
var responseBodyAsText = await response.Content.ReadAsStringAsync();
return responseBodyAsText;
}
else
{
return responsecode +" " +response.ReasonPhrase;
}

接下来,自 HttpClient给你一个 Task<HttpResponseMessage> ,您似乎希望将所有响应都作为字符串,例如 Task<IEnumerable<string>>。 , 正确的?我们可以轻松编写一个函数来转换 Task<HttpResponseMessage>进入Task<string> :

public async Task<string> ReadResultAsync(Task<HttpResponseMessage> responseTask)
{
var response = await responseTask;

var responsecode = (int)response.StatusCode;

if (response.IsSuccessStatusCode)
{
var responseBodyAsText = await response.Content.ReadAsStringAsync();

return responseBodyAsText;
}
else
{
return responsecode + " " + response.ReasonPhrase;
}
}

现在假设您有一些帖子数据集合,您需要将其转化为这个异步字符串集合,称为 myData :

// bear in mind, this code doesn't (necessarily) need to be in a
// method marked "async". If you want to await on resultsTask, though,
// it would need to be in an async method.

var tasks = myData
.Select(x => new FormUrlEncodedContent(x)) // IEnumerable<FormUrlEncodedContent>
.Select(x => client.PostAsync("/mydata", x)) // IEnumerable<Task<HttpResponseMessage>>
.Select(x => ReadResultAsync(x)) // IEnumerable<Task<string>>
.ToArray(); // Task<string>[]

var resultsTask = Task.WhenAll(tasks); // here is Task<string[]>

关于c# - 如何使用 HttpClient() 存储来自多个异步请求的返回数据,直到所有请求完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com