1000个并发Web请求C# [英] 1000 Concurrent Web Request C#
本文介绍了1000个并发Web请求C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我正在尝试生成1000个并发Web请求,然后等待响应。所以基本上我的要求就是有意识地点击n个请求并等待每个人的回复。
我写了下面的代码,但是我无法生成那么多请求。
Hi All,
I am trying to generate 1000 concurrent web request and then waiting for the response.So basically my requirement is to hit n numbers of request sententiously and wait for response of each.
I have written the below code to do so, but I am not able to generate those many request.
static void Main(string[] args)
{
ServicePointManager.DefaultConnectionLimit = 1000000;
ServicePointManager.Expect100Continue = false;
List<HttpWebRequest> request = CreateWebRequest(1000);
TimeMultipleRequests(request);
}
static List<HttpWebRequest> CreateWebRequest(int no)
{
//reading an xml file from location which will be passed to WCF api as http post data
var path = @"D:\PraveenUpadhyay\abc.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
List<HttpWebRequest> webRequest = new List<HttpWebRequest>();
for (int i = 1; i <= no; i++)
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost/TestService.svc/rest/agent/asset");
request.Method = "POST"; request.ContentType = "application/xml;";
var data = Encoding.ASCII.GetBytes(doc.InnerXml);
request.ContentLength = data.Length;
request.Timeout = 1000 * 60 * 10;
//request.KeepAlive = true;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
webRequest.Add(request);
}
return webRequest;
}
private static void TimeMultipleRequests(List<HttpWebRequest> requests)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
foreach (var request in requests)
{
request.GetResponse();
}
stopWatch.Stop();
var timeSpan = stopWatch.Elapsed;
string s = String.Format("{0:00} hours, {1:00} minutes, {2:00} seconds, {3:00} milliseconds", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10);
Console.WriteLine(s);
}
推荐答案
实际上,我只能看到代码中的一个问题:你没有处理可能的异常,所以我我不确定问题到底是怎么出现的。所以,这是我的建议:
- 处理所有线程的顶部堆栈帧上的所有异常 。显示全面的异常信息。以防万一。
- 出于实验目的,增加超时,甚至使其无限。没问题,出于实验目的,即使你在长时间停机的情况下终止你的流程也是可以接受的。
- 在一些知名的高性能网站上测试你的代码,例如Google,Bing,MSDN ...
Actually, I can see only one problem in your code: you did not handle possible exceptions, so I'm not sure how exactly the problem appears. So, here are my suggestions:
- Handle all exceptions on the top stack frame of all threads. Display comprehensive exception information. Just in case.
- For experimental purpose, increase timeout, even make it infinite. No problem, for experimental purpose, it's would be acceptable even if you kill your process in case of prolonged hanging.
- Test your code on some well-known high-performance site, such as Google, Bing, MSDN…
这篇关于1000个并发Web请求C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文