多线程一次性动态启动所有线程

时间:2013-08-30 20:11:25

标签: vb.net multithreading dynamic-programming

我的目标是

  • 检查线程是否是(初始化,活动,开启,什么)
  • 如果他们没有根据需要添加任意数量的线程(最多5个),直到所有线程都启动
  • 如果所有主题都已启动,请重新检查而不会丢失count中的i-loop
  • 此外,这是,因为当所有线程使用相同的子时,如何从Dictionary中删除线程
  

以下代码显示了所有内容,AllOtherThreads sub只是

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

1 个答案:

答案 0 :(得分: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