Matt Wilko
Matt Wilko

Reputation: 27342

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

Upvotes: 0

Views: 2695

Answers (2)

Grant Thomas
Grant Thomas

Reputation: 45058

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.

Upvotes: 2

asawyer
asawyer

Reputation: 17808

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

C# Communication between threads

Upvotes: 1

Related Questions