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

How to store return data from multiple async requests using HttpClient() until all requests complete?

我需要遍历来自 url 的一系列 post 数据请求。请求需要是异步的。检查所有 returns 是否已完成并存储该数据直到所有数据返回的最佳方法是什么?更喜欢使用 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; 
     }

`

编写一个异步函数来触发您的 post 数据(我刚刚使用了您的代码,请添加正确的 error/exception 处理):

async Task<string> PostDataAsync(Dictionary<string, string> postData)
{
    var httpContent = new FormUrlEncodedContent(postData);           
    var response = await client.PostAsync("/mydata", httpContent).ConfigureAwait(false); 

    var responsecode = (int)response.StatusCode; 

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

现在,假设您有一个 post 数据列表“List> postDataCollection”,然后构建您的请求

var postRequests = postDataCollection.Select(pd => PostDataAsync(pd)).ToArray();

然后等待全部完成

var postResponses = await Task.WhenAll(postRequests);

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

 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; 
    }
}

现在假设您有一些 post 数据集合,您需要将其转换为这个异步字符串集合,称为 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[]>