だから私は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
が同時に文字列をダウンロードすることを考えて、どうやらそれは」doesnのこれは実行に2分かかります。何故ですか?コンソールに書き込むことで、順番に実行されていないことがわかりますが、それでも同じ時間がかかります。実際に複数のスレッドを使用して最初の関数のパフォーマンスを向上させるにはどうすればよいですか? ServicePointクラスの
System.Net.ServicePointManager.DefaultConnectionLimit = 5;
チェックアウトServicePointManager.DefaultConnectionLimitとも記事:
ウェブクライアントは一度に1つのリクエストしか処理できないと思います。 –
私は確かに1つしか扱うことができません。しかし、基本的には異なるスレッドで複数のクライアントを使用しているので、複数のクライアントで複数の要求を行うことはできませんか? – nix
タスクは別のスレッドにマップされることもあれば、そうでないこともあります。 –