如何编写在给定线程数中运行程序并显示每个线程所用时间的结果的多线程 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 将记录插入数据库,对于每个线程我传递不同的表(因此表锁不应该成为插入的瓶颈)
我希望所有线程都花费最少的时间,我想它应该是 0.8 秒,当 threadCount 为 1 时。
我是线程新手,如果我在任何地方错了,请纠正我