我正在尝试在应用程序中实现多线程。该应用程序需要创建可变数量的线程,同时传递变量。我可以很容易地创建线程,但我正在试图找到一种方法,可以同时停止所有线程,如果在其中任何一个线程中发现错误,请停止所有线程。
我目前的解决方案是将函数封装在一个循环中,该循环检查布尔值是否为"True",在这种情况下线程会继续。如果出现错误,我会将值更改为"False",所有线程都会停止。类似地,如果我想手动停止线程,我可以从函数中将值设置为"false"。
有没有更好的解决方案,因为主要问题是线程必须在完全停止之前到达循环的末尾?
试试这个
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim foo As New List(Of Threading.Thread)
Threading.Interlocked.Exchange(stopRun, 0L)
For x As Integer = 1 To 5 'start five threads
Dim t As New Threading.Thread(AddressOf workerThrd)
t.IsBackground = True
t.Start()
foo.Add(t) 'add to list
Next
Threading.Thread.Sleep(2000) 'wait two seconds
Threading.Interlocked.Increment(stopRun) 'signal stop
For Each t As Threading.Thread In foo 'wait for each thread to stop
t.Join()
Next
Debug.WriteLine("fini")
End Sub
Dim stopRun As Long = 0L
Private Sub workerThrd()
Do While Threading.Interlocked.Read(stopRun) = 0L
Threading.Thread.Sleep(10) 'simulate work
Loop
Debug.WriteLine("end")
End Sub
在while True块中运行线程应该很好。一旦它为false,您就可以遍历线程并调用thread.abort(),尽管有时使用abort不是一个好主意。使用线程列表可能会有所帮助。我不知道你是如何创建线程的,但这应该很容易理解。
Dim listThreads As List(Of Threading.Thread)
'create/instantiate your threads adding them to the collection something like the following
For i = 1 To numberofthreadsyouneed
Dim tempThread As Threading.Thread = New Threading.Thread
tempThread.Start()
tempThread.Add(tempThread)
next
与其使用while块,不如执行Try catch。在catch内部迭代列表以中止线程
Catch ex As Exception
For each Thread in listThreads
Thread.Abort()
Next
end Try
如果您想要更多的控制
此处
是一个非常可爱的东西,叫做Tasks,它们不久前就发布了。它让你对你的线程有更多的控制
希望这能有所帮助。