HttpClient-发送一批请求 [英] HttpClient - Send a batch of requests
问题描述
我想迭代一批请求,使用HttpClient类将每个请求发送到外部API.
I want to iterate a batch of requests, sending each one of them to an external API using HttpClient class.
foreach (var MyRequest in RequestsBatch)
{
try
{
HttpClient httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMilliseconds(5);
HttpResponseMessage response = await httpClient.PostAsJsonAsync<string>(string.Format("{0}api/GetResponse", endpoint), myRequest);
JObject resultResponse = await response.Content.ReadAsAsync<JObject>();
}
catch (Exception ex)
{
continue;
}
}
这里的上下文是我需要设置一个非常小的超时值,因此,如果响应花费的时间超过该时间,我们只需获取任务已取消"异常并继续进行迭代即可.
The context here is I need to set a very small timeout value, so in case the response takes more than that time, we simply get the "Task was cancelled" exception and continue iterating.
现在,在上面的代码中,注释以下两行:
Now, in the code above, comment these two lines:
HttpResponseMessage response = await httpClient.PostAsJsonAsync<string>(string.Format("{0}api/GetResponse", endpoint), myRequest);
resultResponse = await response.Content.ReadAsAsync<JObject>();
迭代非常快地结束.取消注释它们,然后重试.这需要很多时间.
The iteration ends very fast. Uncomment them and try again. It takes a lot of time.
我想知道是否在等待时调用PostAsJsonAsync/ReadAsAsync方法花费的时间超过了超时值?
I wonder if calling PostAsJsonAsync/ReadAsAsync methods with await takes more time than the timeout value?
基于下面的答案,假设它将创建不同的线程,我们有以下方法:
Based on the answer below, supposing it will create different threads, we have this method:
public Task<JObject> GetResponse(string endPoint, JObject request, TimeSpan timeout)
{
return Task.Run(async () =>
{
try
{
HttpClient httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMilliseconds(5);
HttpResponseMessage response = await httpClient.PostAsJsonAsync<string>(string.Format("{0}api/GetResponse", endPoint), request).WithTimeout<HttpResponseMessage>(timeout);
JObject resultResponse = await response.Content.ReadAsAsync<JObject>().WithTimeout<JObject>(timeout);
return resultResponse;
}
catch (Exception ex)
{
return new JObject() { new JProperty("ControlledException", "Invalid response. ")};
}
});
}
在那里引发一个异常,应该非常快速地返回JObject异常,但是,如果使用httpClient方法,即使它引发了异常,也要花费很多时间.即使返回值只是一个简单的JObject异常,后台处理仍会影响Task.
An exception is raised there and the JObject exception should be returned, very fast, however, if using httpClient methods, even if it raises the exception it takes a lot of time. Is there a behind the scenes processing affecting the Task even if the return value was a simple exception JObject?
如果是,可以使用另一种方法以非常快速的方式向API发送一批请求?
If yes, which another approach could be used to send a batch of requests to an API in a very fast way?
推荐答案
看起来您实际上没有为每个请求运行单独的线程.尝试这样的事情:
It doesn't look like you're actually running a seperate thread for each request. Try something like this:
var taskList = new List<Task<JObject>>();
foreach (var myRequest in RequestsBatch)
{
taskList.Add(GetResponse(endPoint, myRequest));
}
try
{
Task.WaitAll(taskList.ToArray());
}
catch (Exception ex)
{
}
public Task<JObject> GetResponse(string endPoint, string myRequest)
{
return Task.Run(() =>
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsJsonAsync<string>(
string.Format("{0}api/GetResponse", endpoint),
myRequest,
new CancellationTokenSource(TimeSpan.FromMilliseconds(5)).Token);
JObject resultResponse = response.Content.ReadAsAsync<JObject>();
});
}
这篇关于HttpClient-发送一批请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!