在 .NET C# 中使用 httpclient 同时执行 http 请求

Performing concurrently http requests using httpclient in .NET C#

我制作了一个控制台应用程序,基本上可以向我的服务器执行大量请求。每个用户 10-15000 个请求。

所以我编写了这段使用 .NET 的 HTTP 客户端库的代码:

public async Task<string> DoRequest(string token)
{

var request = new HttpRequestMessage(HttpMethod.Post, "mysite.com");
string requestXML = "my xml request goes her...";
request.Content = new StringContent(requestXML, Encoding.UTF8, "text/xml");
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}

所以现在我正在尝试每 1 秒执行尽可能多的 HTTP 请求...我不知道它的上限是多少所以我使用并行 for 循环来加速它:

Parallel.For(0,list.Count(),items=>{
DoRequest(item.Token);
});

但我对代码的速度和发出请求的方式不是很满意...

有什么方法可以加快速度 n 最多可以每 1 秒处理 10-100 个请求?或者最大限制是多少?

有人可以帮我吗?

P.S。伙计们,我只创建了一个 httpclient class 实例,因为我读到只创建一个实例是一个好习惯,因为每次创建这个 class 的新对象时,连接都会关闭,这不是我们想要的不想?

Is there any way that I can speed things up n do maybe up to 10-100 requests per 1 second?

这是一个无法回答的问题。

Or what is the maximum limit?

正如大卫所说,您需要设置 ServicePointManager.DefaultConnectionLimit。这应该足以作为 Main 方法中的第一行:

ServicePointManager.DefaultConnectionLimit = int.MaxValue;

I've used parallel for loop to speed this

这项工作的工具不正确。您确实需要并发性,但不需要并行性。异步并发使用Task.WhenAll:

表示
var tasks = list.Select(item => DoRequest(item.Token));
await Task.WhenAll(tasks);

I created only one instance of httpclient class because I read that it's a good practice to make only one since each time a new object of this class is made the connection gets closed, which is not what we want no?

没错。