该操作已在System.net.httpwebrequest.getResponse()上发布,同时将大量请求发送到主机



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

我尝试了通常的嫌疑犯,例如增加 defaultConnectionLimit ,关闭Web响应对象。由于请求在服务器上不需要太多时间,因此我还将请求 timeout readwriteTimeout 设置为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或10。

如果您要对该Web服务进行50个并行电话,则应将ServicePointManager.DefaultConnectionLimit(在App Startup(设置为更大的数字(例如40-50(。

此外,您没有在request上调用CloseDispose。您应该这样做,或者让using为您照顾。

相关内容

  • 没有找到相关文章

最新更新