2011-03-18 186 views
0

我剛剛在VB.net中學習了一些多線程的基礎知識,最近我遇到了處理大型記錄列表並逐個將它們插入到SQL數據庫中的問題。 我有代碼看起來是這樣的:多線程處理問題

Private Sub btnLoadNow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadNow.Click 

    Dim autoLoad1 As New Thread(AddressOf AutoLoad) 
    autoLoad1.Start() 

    Dim autoLoad2 As New Thread(AddressOf AutoLoad) 
    autoLoad2.Start() 

    Dim autoLoad3 As New Thread(AddressOf AutoLoad) 
    autoLoad3.Start() 

    Dim autoLoad4 As New Thread(AddressOf AutoLoad) 
    autoLoad4.Start() 

    Dim autoLoad5 As New Thread(AddressOf AutoLoad) 
    autoLoad5.Start() 


    Dim autoLoad6 As New Thread(AddressOf AutoLoad) 
    autoLoad6.Start() 

    Dim autoLoad7 As New Thread(AddressOf AutoLoad) 
    autoLoad7.Start() 

    Dim autoLoad8 As New Thread(AddressOf AutoLoad) 
    autoLoad8.Start() 

    Dim autoLoad9 As New Thread(AddressOf AutoLoad) 
    autoLoad9.Start() 

End Sub 

Private Sub AutoLoad() 

for each Item as Record In ItemLists 
    Process Codes 
Next 

End Sub 

的項目列表是一個全局列表我從數據庫中檢索,一切看起來好像沒什麼問題,但是當我運行這個程序,我發現線程插入一個記錄9次進入數據庫(我總共有9個線程),這讓我想我可能需要專門爲每個線程分配1/9的列表?是否有另一種方式來做到這一點,如果不需要分割列表,我如何分割它然後分配?任何幫助將受到歡迎。

回答

0

我不會爲每個插件創建一個線程,因爲創建線程的開銷超過了您首先將其旋轉的好處。但是,您可以使用共享變量並使用SyncLock來保持併發性。

編輯評論問:

'Replace List(Of String) with your type. 
Public Shared ItemList As New List(Of String) 

這通常用於爭奪對內存的更新。你的第一個線程最終會在你的例子中完成所有的處理。如果您真的想旋轉幾個線程並分割工作,請爲每個線程分配一個名稱,然後讓您的過程保持邏輯以將不同的工作分配給每個線程。

+0

我確實在循環代碼中有synclock。你介意給我一個使用共享變量的例子嗎?謝謝。 – miketonny 2011-03-18 03:59:01