2013-08-30 78 views
2

我的目標是多線程開始,所有線程同時動態

  • 檢查線程,如果他們的東西(initiallized,活的,對了,什麼都)
  • 如果不添加儘可能多的線程數直到需要的所有線程都開始
  • 如果所有線程被啓動(最多5),複檢的w/o失去一個counti-loop
  • 此外,這是,因爲如何當所有線程都使用相同的子

下面的代碼顯示了從字典中刪除線程,AllOtherThreads子簡直是

Sub AllOtherThreads(ByVal i As Integer) 
    For z = 0 To 500 
     For q = 0 To 500 
      For w = 0 To 500 
       SomethingInvoked_Invoke(i, z, qt, wt) 
      Next 
     Next 
    Next 
End Sub 

主代碼

For i = 0 To 500 
    Recheck: 
     For izt = 0 To 2 
      If dictThread.Values(izt) Is Nothing Then 
       dictThread.Add("Thread" & izt.ToString, New Thread(New ParameterizedThreadStart(AddressOf AllOtherThreads))) 
       dictThread.Values(izt).Start(i) 
       GoTo nexti 
      ElseIf dictThread.Values(izt).IsAlive = False Then 

       dictThread.Remove(dictThread.Keys(izt)) 

在下面的行是發生錯誤Thread is running or terminated; it cannot restart.

   dictThread.Values(izt).Start(i) 
       GoTo nexti 
      End If 
     Next 
     System.Threading.Thread.Sleep(100) 
     GoTo Recheck 
    nexti: 
    Next 
+0

什麼是你想回答這個問題嗎?你問如何啓動多線程而不硬編碼? – camerondm9

+0

我會更好地指向他們 –

+0

您只需要啓動線程一次,而您在創建時只需要一次。線程無法重新啓動,因此如果您想再次運行該代碼,則需要創建一個新線程。 – camerondm9

回答

2

線程可以不被重新啓動。如果您需要再次運行該代碼,請創建一個新線程。
在你的情況,你可能想從詞典中刪除舊的項,然後重新創建它:

For i = 0 To 500 
Recheck: 
    For izt = 0 To 2 
     If dictThread.Values(izt) Is Nothing Then 
      dictThread.Add("Thread" & izt.ToString, New Thread(New ParameterizedThreadStart(AddressOf AllOtherThreads))) 
      dictThread.Values(izt).Start(i) 
      GoTo nexti 
     ElseIf dictThread.Values(izt).IsAlive = False Then 
      Dim values As String = dictThread.Keys(izt) 
      'Remove old thread 
      dictThread.Remove(values) 
      'Create new thread 
      dictThread.Add(values, New Thread(New ParameterizedThreadStart(AddressOf AllOtherThreads))) 
      'Start new thread 
      dictThread.Values(izt).Start(i) 
      GoTo nexti 
     End If 
    Next 
    System.Threading.Thread.Sleep(100) 
    GoTo Recheck 
nexti: 
Next