【发布时间】:2019-09-27 15:11:28
【问题描述】:
我需要从抵押 API 中提取自定义字段。 问题是总共有 11000 条记录,每个 API 请求需要 1 秒。我想找到一种异步并行发送请求的方法,以提高效率。
我尝试遍历所有请求,然后使用Task.WaitAll() 等待响应返回。我只收到两个响应,然后应用程序无限期地等待。
我首先为HttpClient设置了一个静态类
public static class ApiHelper
{
public static HttpClient ApiClient { get; set; }
public static void InitializeClient()
{
ApiClient = new HttpClient();
ApiClient.DefaultRequestHeaders.Add("ContentType", "application/json");
}
}
我收集我的抵押 ID 列表并循环通过 API Post Calls
static public DataTable GetCustomFields(DataTable dt, List<string> cf, string auth)
{
//set auth header
ApiHelper.ApiClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", auth);
//format body
string jsonBody = JArray.FromObject(cf).ToString();
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var responses = new List<Task<string>>();
foreach (DataRow dr in dt.Rows)
{
string guid = dr["GUID"].ToString().Replace("{", "").Replace("}", ""); //remove {} from string
responses.Add(GetData(guid, content));
}
Task.WaitAll(responses.ToArray());
//some code here to process through the responses and return a datatable
return updatedDT;
}
每个 API 调用都需要 URL 中的抵押 ID (GUID)
async static Task<string> GetData(string guid, StringContent json)
{
string url = "https://api.elliemae.com/encompass/v1/loans/" + guid + "/fieldReader";
Console.WriteLine("{0} has started .....", guid);
using (HttpResponseMessage response = await ApiHelper.ApiClient.PostAsync(url, json))
{
if (response.IsSuccessStatusCode)
{
Console.WriteLine("{0} has returned response....", guid);
return await response.Content.ReadAsStringAsync();
}
else
{
Console.WriteLine(response.ReasonPhrase);
throw new Exception(response.ReasonPhrase);
}
}
}
我现在只测试 10 条记录并发送所有 10 条请求。 但我只收到两回。
结果是here。
您能否告诉我发送并发 API 调用的正确方法?
【问题讨论】:
-
看看TPL DataFlow
标签: c# api httpclient