安全中止ThreadList中的线程

时间:2018-08-16 14:09:31

标签: vb.net multithreading

正在使用线程列表,因此可以应用户的请求中止线程。到目前为止,我已经移植了一些代码来杀死进程(也基于安全地删除列表项),但是它并没有终止任何线程。在从0到Threadlist.Count的循环中单独使用try catch会中止线程,但也会导致与使用已删除其元素的列表有关的异常。以下代码中有什么我做错的事情吗?

        For x As Integer = threadList.Count - 1 To 0 Step -1
            Dim tid As String = threadList(x).ManagedThreadId
            For Each t As Thread In threadList
                If tid = t.ManagedThreadId.ToString Then
                    Try
                        t.Abort()
                        threadList.RemoveAt(x)
                    Catch ex As ThreadAbortException
                        'ex.ToString()
                    End Try
                End If
            Next
        Next

2 个答案:

答案 0 :(得分:2)

您不能从For Each循环中使用的列表中删除项目。获取要删除的线程,然后将其删除。

        Dim threadToRemove As Thread = Nothing

        ' First, find the thread to remove
        For Each t As Thread In threadList
            If tid = t.ManagedThreadId.ToString Then
                threadToRemove = t
                Exit For
            End If
        Next

        ' Then, remove the thread
        If threadToRemove IsNot Nothing Then
                Try
                    t.Abort()
                    threadList.Remove(threadToRemove)
                Catch ex As ThreadAbortException
                    'ex.ToString()
                End Try
        End If

通过分裂逻辑就可以了。然后,您可以根据需要将这两部分放入方法中。

我不知道这段代码是否可以解决您的问题,但希望您能理解。循环执行两次threadList只会以一种复杂的方式删除所有线程。

答案 1 :(得分:-1)

感谢@the_lotus,下面是经过调试的代码,该代码使ThreadList中的线程可以安全地中止:

            For x As Integer = threadList.Count - 1 To 0 Step -1
                Dim tid As String = threadList(x).ManagedThreadId
                Dim t As Thread = Nothing
                ' First, find the thread to remove
                Dim threadToRemove As Thread = Nothing
                For Each t In threadList
                    If tid = t.ManagedThreadId.ToString Then
                        threadToRemove = t
                        Exit For
                    End If
                Next
                ' Then, remove the thread
                If threadToRemove IsNot Nothing Then
                    Try
                        threadToRemove.Abort()
                        threadList.Remove(threadToRemove)
                    Catch ex As ThreadAbortException
                        'ex.ToString()
                    End Try
                End If
            Next