0

指定された数のスレッドでプログラムを実行し、各スレッドからかかった時間の結果を表示するマルチスレッドWindowsアプリケーションを作成する方法。作成しようとしましたが、プログラムの結果が正しくないことがわかります。つまり、スレッド数を増やすと、各スレッドにかかる時間も長くなります(メッセージボックスに表示されます)。以下は私のコードです:

private static void StartMultithread(long recordsToProcess, string connectionString, string stagingTableName, bool tableLockEnabled, bool transactionEnabled, int batchSize, bool userMultipleDatabases, bool userMultipleTables, bool userMultipleUsers, int bulkInsertTimeout)
 {
 Dictionary<string, Thread> threadPool = new Dictionary<string, Thread>();
 for (int i = 0; i < threadCount; i++)
 {
     Thread thread = new Thread(new ParameterizedThreadStart(delegate(object tid)
     {
         int ii = (int)tid;
         Core.BulkInsert bulkInsert1 = new Core.BulkInsert();
         string result1 = bulkInsert1.Insert(recordsToProcess, connectionString, stagingTableName, tableLockEnabled, transactionEnabled, batchSize, bulkInsertTimeout);
         MessageBox.Show (result1);
     }));

     thread.Name = i.ToString();
     threadPool.Add(thread.Name, thread);
 }

 for (int i = 0; i < threadCount; i++)
 {
     Thread thread = threadPool[i.ToString()];
     thread.IsBackground = true;
     thread.Start(i);
 }

 for (int i = 0; i < threadCount; i++)
 {
     Thread thread = threadPool[i.ToString()];
     thread.Join();
 }
}

結果として、threadCount = 1を指定すると、所要時間は0.8秒になります。2の場合、両方のスレッドにかかる時間はそれぞれ約1.2秒です。3の場合、個別にかかる時間は約1.7秒です。

Bulkinsert1.Insertは、レコードをデータベースに挿入します。スレッドごとに、異なるテーブルを渡します(テーブルロックが挿入のボトルネックにならないようにするため)。

すべてのスレッドに最小限の時間がかかるようにしたいのですが、threadCountが1の場合、0.8秒かかると思います。

私は糸脱毛に不慣れです、私がどこかで間違っているならば私を訂正してください

4

1 に答える 1

1

提供されたコードからは明らかではないため、どのようにタイミングを計っているのかわかりません。

ただし、これが IO 集約型の操作であると仮定bulkInsert1.Insertすると (つまり、スレッドはほとんどの場合、IO 操作が完了するまで待機することを意味します)、スレッドの数を増やすと完了時間が長くなるのは正常です。より多くのスレッドがありますが、一部の共有リソース (MB バス、ネットワーク カード、リモート データベースなど) を使用しています。たとえば、データベースが挿入操作を処理するのに 0.8 秒かかる場合、同じことを行う 2 つ以上の同時接続を処理するのに時間がかかるのは正常です。特に、これらのクエリが何らかの理由で互いにブロックされている場合は特にそうです。 . その結果、スレッドの完了時間が長くなります。

于 2012-06-18T11:14:42.367 に答える