我正在尝试在应用程序中实现多线程.应用程序需要创建可变数量的线程,同时传递变量.我可以轻松地创建线程,但是我试图找到一种能够立即停止所有线程的方法,如果在这些线程中的任
我目前的解决方案是将函数包含在一个循环中,该循环检查布尔值是否为“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