【发布时间】:2012-06-20 07:52:53
【问题描述】:
如何编写在给定线程数中运行程序并显示每个线程所用时间的结果的多线程 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 时。
我是线程新手,如果我在任何地方错了,请纠正我
【问题讨论】:
-
你有多少个 CPU 内核?如果你只有一个,那么任何时候任何一个线程都只能在一个 CPU 上运行。您至少需要两个核心才能看到这方面的任何改进。
-
创建线程需要一些时间。请改用 System.Threading.ThreadPool.QueueUserWorkItem,这样您将在应用启动时使用 CLR 已创建的线程。
-
顺便说一句,你用什么课来保证你的时间?如果您还没有,您可能应该使用 System.Diagnostics.Stopwatch。
-
我使用的是同一个秒表
-
标题错误。你应该问为什么时间在增加。由于共享资源,时间增加。
标签: c# .net winforms multithreading