如何編寫多線程窗口應用程序,該應用程序在給定數量的線程中運行程序並顯示從每個線程獲取的時間結果。我試圖創建它,但我可以看到我的程序顯示的結果不正確,這意味着當我增加線程數時,每個線程所用的時間也會增加(如消息框所示)。以下是我的代碼:爲什麼隨着線程數量的增加,我的多線程示例中的時間不斷增加
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。您至少需要兩個內核才能看到這方面的改進。 – Default
創建線程需要一些時間。改爲使用System.Threading.ThreadPool.QueueUserWorkItem,這樣您就可以在應用程序啓動時使用CLR創建的線程。 –
你正在用什麼課程來讓你的時間敏捷btw?如果你還沒有,你應該使用System.Diagnostics.Stopwatch。 –