gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:30:49 26 4
gpt4 key购买 nike

我制作了一个控制台应用程序,它基本上向我的服务器执行大量请求。每个用户 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 个请求?或者最大限制是多少?

谁能帮帮我?

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

最佳答案

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?

正如 David 所说,您需要设置 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?

没错。

关于c# - 在 .NET C# 中使用 httpclient 同时执行 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42935059/

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