2

我的目标是

  • 检查线程是否是某物(已初始化、活动、打开、任何情况)
  • 如果他们没有根据需要添加尽可能多的线程(最多 5 个),直到所有线程都启动
  • count如果所有线程都已启动,请重新检查 w/o 丢失i-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
4

1 回答 1

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
于 2013-09-03T17:30:51.537 回答