为什么使用多线程没有提高性能?
Why is using multiple threads not improving performance?
所以我一直在尝试使用 c# WebClient
。我设法用类似于这样的代码制作了一个工作程序(控制台应用程序):
static void Search(string number)
{
using (var client = new WebClient())
{
for (int a = 0; a < globalvariable.lenght; a++)
{
string toWrite = "nothing";
for (int b = 0; a < globalvariable2.lenght; b++)
{
string result = client.DownloadString(urlString);
//do stuff with toWrite if page is not empty
//change toWrite and break the b loop
}
Console.WriteLine(toWrite);
}
}
}
它不是真的很快所以我想我可以通过使用多线程来让它更快。
执行需要2分钟。
所以我尝试将循环设为 Parallel.For
循环。仍然需要2分钟才能执行。所以我在这里阅读了一些东西并编写了以下代码:
static async Task AWrite(string number, int a)
{
using (var client = new WebClient())
{
string toWrite = "nothing";
for(int b=0; a<globalvariable2.lenght; b++)
{
string result = await client.DownloadStringTaskAsync(uri);
//do stuff with toWrite if page is not empty
//change toWrite and break the b loop
}
Console.WriteLine(toWrite);
}
}
然后是调用它的函数:
private static void ASearch(string number)
{
var tasks = new List<Task>();
for(int a=0; a<gobalvariable.Length; a++)
{
tasks.Add(AWrite(number, a));
}
Task.WaitAll(tasks.ToArray());
}
所以我认为多个 WebClient
会同时下载字符串,显然这不会发生,因为这也需要两分钟的时间来执行。这是为什么?通过在控制台中的写入,我知道它们没有按顺序执行,但仍然需要相同的时间。我怎样才能通过使用多线程实际提高第一个函数的性能?
您可以更改 HTTP 连接限制:
System.Net.ServicePointManager.DefaultConnectionLimit = 5;
查看 ServicePointManager.DefaultConnectionLimit and also the article on the ServicePoint class。使用此 属性 您可以更改 HTTP 连接的默认连接限制。
最终限制在我下载的网站上。它限制为每人 1 个 HTTP 连接。谢谢你的想法。
所以我一直在尝试使用 c# WebClient
。我设法用类似于这样的代码制作了一个工作程序(控制台应用程序):
static void Search(string number)
{
using (var client = new WebClient())
{
for (int a = 0; a < globalvariable.lenght; a++)
{
string toWrite = "nothing";
for (int b = 0; a < globalvariable2.lenght; b++)
{
string result = client.DownloadString(urlString);
//do stuff with toWrite if page is not empty
//change toWrite and break the b loop
}
Console.WriteLine(toWrite);
}
}
}
它不是真的很快所以我想我可以通过使用多线程来让它更快。 执行需要2分钟。
所以我尝试将循环设为 Parallel.For
循环。仍然需要2分钟才能执行。所以我在这里阅读了一些东西并编写了以下代码:
static async Task AWrite(string number, int a)
{
using (var client = new WebClient())
{
string toWrite = "nothing";
for(int b=0; a<globalvariable2.lenght; b++)
{
string result = await client.DownloadStringTaskAsync(uri);
//do stuff with toWrite if page is not empty
//change toWrite and break the b loop
}
Console.WriteLine(toWrite);
}
}
然后是调用它的函数:
private static void ASearch(string number)
{
var tasks = new List<Task>();
for(int a=0; a<gobalvariable.Length; a++)
{
tasks.Add(AWrite(number, a));
}
Task.WaitAll(tasks.ToArray());
}
所以我认为多个 WebClient
会同时下载字符串,显然这不会发生,因为这也需要两分钟的时间来执行。这是为什么?通过在控制台中的写入,我知道它们没有按顺序执行,但仍然需要相同的时间。我怎样才能通过使用多线程实际提高第一个函数的性能?
您可以更改 HTTP 连接限制:
System.Net.ServicePointManager.DefaultConnectionLimit = 5;
查看 ServicePointManager.DefaultConnectionLimit and also the article on the ServicePoint class。使用此 属性 您可以更改 HTTP 连接的默认连接限制。
最终限制在我下载的网站上。它限制为每人 1 个 HTTP 连接。谢谢你的想法。