C# 具有不同代理的并行异步HttpWebRequests。如何最大化性能?
我正在编写一个应用程序,需要从不同的代理向博彩网站执行大量并行httpwebrequests。我之所以使用不同的代理,是因为如果有很多请求,收受赌注者可以禁止ip。我的目标是尽快获得最新鲜的网站内容。 以下是我的代码和所有设置:C# 具有不同代理的并行异步HttpWebRequests。如何最大化性能?,c#,performance,asynchronous,proxy,httpwebrequest,C#,Performance,Asynchronous,Proxy,Httpwebrequest,我正在编写一个应用程序,需要从不同的代理向博彩网站执行大量并行httpwebrequests。我之所以使用不同的代理,是因为如果有很多请求,收受赌注者可以禁止ip。我的目标是尽快获得最新鲜的网站内容。 以下是我的代码和所有设置: ServicePointManager.DefaultConnectionLimit = 1000; ServicePointManager.Expect100Continue = false; ServicePointM
ServicePointManager.DefaultConnectionLimit = 1000;
ServicePointManager.Expect100Continue = false;
ServicePointManager.UseNagleAlgorithm = false;
for (var i = 0; i < proxyCollection.Count; i++)
{
var proxyLocal = proxyCollection[i];
var iLocal = i;
Task.Run(async () =>
{
var httpWebRequest = (HttpWebRequest) WebRequest.Create(String.Format("https://bookmaker.com/page{0}", iLocal));
httpWebRequest.Proxy = proxyLocal;
httpWebRequest.PreAuthenticate = true;
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var httpWebResponse = (HttpWebResponse) await httpWebRequest.GetResponseAsync())
using (var responseStream = httpWebResponse.GetResponseStream())
using (var streamReader = new StreamReader(responseStream))
{
var stringContent = await streamReader.ReadToEndAsync();
//Here i'm processing new data. It works pretty fast, so this isn't a problem
ProcessStringContent(stringContent);
}
});
}
这段代码并没有我想象的那么快
第一个问题是,奇怪的是,所有请求并不是一次启动的。正如我在TaskManager中看到的,加载有两个或更多的最大值。我有一个真正快速的代理,proxyCollection包含它。但是如果我在上面的代码之后使用wait Task.Delay5000,在某些情况下,当5000ms通过我的快速代理的请求时,甚至不会启动
第二个问题是所有任务执行的总时间都很慢。我预计,如果一个请求需要200-300ms来执行,那么100个以上的并行和异步请求需要多一点时间。但有些时候,这更多的是10-20倍。我怀疑出了什么事
第三个问题是,当我运行这段代码时,它会冻结UI,而不是完全冻结,但UI会滞后。我读到WebRequest.Create是同步处理的,可以获得一些时间进行dns查找、代理设置e.t.c,如果我提出很多请求,他们也可以简单地填充我的所有线程UI线程来创建WebRequests。但我尝试创建指向ip地址WebRequest.CreateString.Fo的请求rmathttps://10.10.10.1/page{0},iLocal-没有任何更改,我正在设置代理,这样就不需要自动检测代理,所以我不明白为什么创建会花费这么多时间,并且创建或可能与smth else?有关
有人能告诉我我做错了什么吗?我在所有ServicePointManager设置中迷失了方向。我尝试的所有设置都没有帮助。Net能处理这样的任务吗?或者我需要使用nodejs来获得最佳性能
附言:代理的集合并没有这么大,50-100个不同的代理
例如:
Parallel.For(0, 10, delegate(int i) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri("http://www.mysi.com"));
string dataToSend = "Data";
byte[] buffer = System.Text.Encoding.GetEncoding(1252).
GetBytes(dataToSend);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;
request.Host = "www.mysite.com";
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
});
你能解释一下这篇文章的意思吗?谢谢。如果您使用async/wait,我们需要使用Parallel,而不是Task.RunHm。并行和任务之间有什么区别吗?运行吗?我不确定,但并行处理也适用于任务。这对我有什么帮助?谢谢,很有趣。你能告诉我在哪里可以读到关于这个任务的信息吗?Run和async/await不能很好地工作?我真的很惊讶。谢谢。您也可以尝试使用Task.whall代替Task.Run