2012-06-18 47 views
0

如何編寫多線程窗口應用程序,該應用程序在給定數量的線程中運行程序並顯示從每個線程獲取的時間結果。我試圖創建它,但我可以看到我的程序顯示的結果不正確,這意味着當我增加線程數時,每個線程所用的時間也會增加(如消息框所示)。以下是我的代碼:爲什麼隨着線程數量的增加,我的多線程示例中的時間不斷增加

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給出

我新的線程,請糾正我,如果我錯了,任何地方

+0

你有多少個CPU核心?如果您只有一個線程,則任何一個線程都只能運行一個CPU。您至少需要兩個內核才能看到這方面的改進。 – Default

+0

創建線程需要一些時間。改爲使用System.Threading.ThreadPool.QueueUserWorkItem,這樣您就可以在應用程序啓動時使用CLR創建的線程。 –

+0

你正在用什麼課程來讓你的時間敏捷btw?如果你還沒有,你應該使用System.Diagnostics.Stopwatch。 –

回答

1

我不知道你是如何計時的東西,因爲它不是顯而易見的代碼提供。

但是,假設bulkInsert1.Insert是一個IO密集型操作(意味着您的線程大多等待IO操作完成),則完成時間隨着您增加線程數量而增加是正常的。您有更多的線程,但他們正在使用一些共享資源(例如MB總線,網卡,遠程數據庫等)。例如,如果數據庫需要0.8s來處理插入操作,那麼處理兩個或更多同時執行相同操作的連接需要更長的時間是正常的 - 特別是如果由於某些原因這些查詢碰巧發生了阻塞。因此,線程的完成時間會增加。

+0

bulkinsert1插入記錄到數據庫,對於每個線程我傳遞不同的表(因此表鎖不應該是插入的瓶頸) –

+1

@ImranRizvi如上所述,阻塞只是一個例子。不同的表格並不意味着沒有其他共享資源。 –

相關問題