微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我可以立即停止运行.NET的线程吗

如何解决我可以立即停止运行.NET的线程吗

| 我在线程中运行以下代码以枚举Active Directory中的本地计算机。这需要一些时间才能完成(大约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()
    

解决方法

如果您使用的是BackgroundWorker线程,则该线程支持取消操作,请参见此答案 线程之间的C#通信     ,这个想法可能是管理一个
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作为取消逻辑的一部分,并希望该过程更快停止。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。