Search code examples
vb.netmultithreadingvisual-studio-2010abort

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

Solution

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

    C# Communication between threads