0

我在线程中运行以下代码来枚举活动目录中的本地机器。这需要一些时间才能完成(大约 5-10 秒),因此如果用户在枚举完成之前退出应用程序,则应用程序需要 5-10 秒才能退出。我尝试了 thread.abort 但因为它正在等待For Each SubChildEntry In SubParentEntry.Children完成它在返回之前不会中止。

    Dim childEntry As DirectoryEntry = Nothing
    Dim ParentEntry As New DirectoryEntry

        ParentEntry.Path = "WinNT:"
        For Each childEntry In ParentEntry.Children
            Windows.Forms.Application.DoEvents()
            Select Case childEntry.SchemaClassName
                Case "Domain"
                    Dim SubChildEntry As DirectoryEntry
                    Dim SubParentEntry As New DirectoryEntry
                    SubParentEntry.Path = "WinNT://" & childEntry.Name

                    'The following line takes a long time to complete
                    'the thread will not abort until this returns
                    For Each SubChildEntry In SubParentEntry.Children 
                        Select Case SubChildEntry.SchemaClassName
                            Case "Computer"
                                _collServers.Add(SubChildEntry.Name.ToUpper)

                        End Select
                    Next

            End Select
        Next

        RaiseEvent EnumComplete()
4

2 回答 2

2

这个想法可能是管理一个CancelPending可以安全设置和检查的属性,以查看是否应该继续执行:

For Each j In k

    If (CancelPending) Then
        Exit For
    End If

    ...

    Select ...
        Case "a"
            ...
            For Each x In y
                If (CancelPending) Then
                    Exit For
                End If

                ...
            Next
    End Select
Next

您可以将其设置CancelPending为 true 作为取消逻辑的一部分,并期望该过程更快停止。

于 2011-05-25T11:40:17.633 回答
1

如果您使用的是 BackgroundWorker 线程,它支持取消,请参阅此答案

C#线程之间的通信

于 2011-05-25T11:33:55.950 回答