Vb.net 我可以立即停止运行.NET的线程吗
我在一个线程中运行以下代码,以枚举active directory中的本地计算机。这需要一些时间来完成(大约5-10秒),因此如果用户在枚举完成之前退出应用程序,则应用程序需要5-10秒退出。我尝试了thread.abort,但因为它正在等待subparentry.Children中的每个subchildrentry的Vb.net 我可以立即停止运行.NET的线程吗,vb.net,multithreading,visual-studio-2010,abort,Vb.net,Multithreading,Visual Studio 2010,Abort,我在一个线程中运行以下代码,以枚举active directory中的本地计算机。这需要一些时间来完成(大约5-10秒),因此如果用户在枚举完成之前退出应用程序,则应用程序需要5-10秒退出。我尝试了thread.abort,但因为它正在等待subparentry.Children中的每个subchildrentry的,所以在返回之前,它不会中止 Dim childEntry As DirectoryEntry = Nothing Dim ParentEntry As New D
,所以在返回之前,它不会中止
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线程,它支持取消,请参阅此答案
如果您使用的是BackgroundWorker线程,它支持取消,请参阅此答案
这个想法可能是管理一个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,并期望进程更快地停止。可以管理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,并期望进程更快地停止。您可以向我们展示您用于创建和启动新线程的代码吗?您可以向我们展示您用于创建和启动新线程的代码吗?我有这个想法,但每个x In y
行的,都是最重要的响应时间,因此If(CancelPending)在完成之前不会执行,我有这个想法,但正是每个x In y
行的需要时间响应,因此If(CancelPending)然后
在完成之前不会执行我已将代码更改为使用后台工作程序-这现在按预期工作-谢谢我已将代码更改为使用后台工作程序-这现在按预期工作-谢谢