首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以立即停止线程运行.NET吗?

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

Stack Overflow用户
提问于 2011-05-25 19:26:26
回答 2查看 2.6K关注 0票数 0

我在线程中运行以下代码,以枚举active directory中的本地计算机。这需要一些时间来完成(大约5-10秒),所以如果用户在枚举完成之前退出应用程序,应用程序需要5-10秒才能退出。我尝试过thread.abort,但因为它正在等待For Each SubChildEntry In SubParentEntry.Children完成,所以直到它返回时才中止。

代码语言:javascript
复制
    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()
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-05-25 19:33:56

如果您使用的是BackgroundWorker线程,它支持取消,请参阅此答案

C# Communication between threads

票数 1
EN

Stack Overflow用户

发布于 2011-05-25 19:40:18

其想法可能是管理一个CancelPending属性,该属性可以安全地设置和检查,以查看是否应该继续执行:

代码语言:javascript
复制
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作为取消逻辑的一部分,并期望该过程更快地停止。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6123716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档