我正在向具有不同数据的特定 Web 服务发送大量同时请求。为了实现这一点,我创建了许多线程(数量大约 50 个)。每分钟的请求总数可能会增加到 10000。
Windows服务形式的应用程序运行良好几分钟,然后遇到操作超时错误。
我尝试过常见的怀疑,例如增加默认连接限制,关闭网络响应对象。由于请求在服务器上花费的时间并不多,因此我还设置了请求Timeout and 读写超时至 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).
此外,您没有调用Close
or Dispose
on request
。你应该这样做,或者让using为您照顾。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)