gpt4 book ai didi

c# - 向主机发送大量请求时,System.Net.HttpWebRequest.GetResponse() 操作超时

转载 作者:行者123 更新时间:2023-12-02 20:30:53 25 4
gpt4 key购买 nike

我正在向具有不同数据的特定 Web 服务发送大量同时请求。为了实现这一点,我创建了许多线程(数量大约 50 个)。每分钟的请求总数可能会增加到 10000。Windows服务形式的应用程序运行良好几分钟,然后遇到操作超时错误。

我尝试了常见的方法,例如增加DefaultConnectionLimit、关闭网络响应对象。由于请求在服务器上花费的时间并不多,因此我还将请求 TimeoutReadWriteTimeout 设置为 5 秒。下面是不同线程重复调用的代码片段。

// Below line is executed at the start of application
ServicePointManager.DefaultConnectionLimit = 15000;

// Below code is executed at repeatedly by different threads
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Host = hostName;
request.Proxy = null;
request.UserAgent = "Windows Service";
byte[] bytes = new byte[0];
if (body != null)
{
bytes = System.Text.Encoding.ASCII.GetBytes(body);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
}
request.Method = "POST";
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;

request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));

request.CookieContainer = this.cookieContainer;

if (body != null)
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}

HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
httpResponse.Close();

最佳答案

ServicePointManager.DefaultConnectionLimit 限制向给定服务器发出的 Web 请求的数量。默认一般为2 or 10 .

如果您要对该 Web 服务进行 50 次并行调用,则应将 ServicePointManager.DefaultConnectionLimit(在应用启动时)设置为更大的数字(例如 40-50 )。

此外,您没有根据请求调用CloseDispose。你应该这样做,或者让using为您处理好。

关于c# - 向主机发送大量请求时,System.Net.HttpWebRequest.GetResponse() 操作超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785681/

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