2011-05-25 77 views
0

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

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

你能告诉我们你用来创建和启动一个新线程的代码吗? – 2011-05-25 11:30:01

回答

1

如果您使用的是BackgroundWorker的线程,它可以支持取消,看到这个答案

C# Communication between threads

+0

我已经改变了代码使用后台工作人员 - 这是现在按预期工作 - 谢谢 – 2011-05-25 12:03:29

2

的想法可能是管理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真为你着性的一部分逻辑推理并期望该过程尽快停止。

+0

我有这个想法,但它是'对于每一个x在y'行,正在花时间来响应,所以'If(CancelPending )然后'在执行完成之前不会执行 – 2011-05-25 11:57:05