开发者

Can I immediately stop a thread from running .NET

I have the following code running in a thread to enumerate the local machines in the active directory. This takes some time to complete (about 5-10 seconds) so if the user quits the application before the enum is complete the application takes 5-10 seconds to quit. I tried thread.abort but because it is waiting for For Each SubChildEntry In SubParentEntry.Children to complete it doesn't abort until this returns.

    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()


The idea might be to manage a CancelPending property that can be safely set and checked to see whether execution should proceed, or not:

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

You can set CancelPending to true as part of your cancellation logic and expect the process to halt sooner.


If you are using a BackgroundWorker thread, it supports canceling, see this answer

C# Communication between threads

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜