0

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()
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143

2 Answers2

2

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.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • I had this idea but it is the `For Each x In y` line that is taking the time to respond so the `If (CancelPending) Then` doesn't execute until it has finished – Matt Wilko May 25 '11 at 11:57
1

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

C# Communication between threads

Community
  • 1
  • 1
asawyer
  • 17,642
  • 8
  • 59
  • 87