我有一个产生多个线程的线程。 如何确定所有线程是否完成? 所有线程完成后我必须调用一个方法。 这不是重复的 喜欢
dim thread1.start()
dim thread2.start()
if (all threads are finished)
muFunc()
end if
您可以在下方看到示例代码段。 see the code here
这就是我被困的地方。 我该怎么办? 提前谢谢。
答案 0 :(得分:0)
从任何地方调用此方法(Form.Load,Button.Click ...)
调用者事件处理程序/方法不需要是异步调用者
ThreadPoolManager()
定义包含线程池的List(Of Thread)
的范围
Dim ThreadPool As List(Of Thread)
ThreadPoolManager()
(a)等待StartThreads()
,它启动ThreadPool
列表中的所有线程。 Async方法返回时,然后调用MyFunctionWhenAllThreadsAreFinished()
Private Async Sub ThreadPoolManager()
If Await StartThreads() = True Then
MsgBox("All Finished!", MsgBoxStyle.OkOnly, "Finally!")
Call MyFunctionWhenAllThreadsAreFunished()
Else
MsgBox("Something went wrong!", MsgBoxStyle.OkOnly, "Damn it!")
End If
End Sub
StartThreads()
方法初始化ThreadPool中的所有线程,并使用委托工作方法在线程启动时调用
Protected Async Function StartThreads() As Task(Of Boolean)
ThreadPool = New List(Of Thread)
Dim MyThread1 As Thread = New Thread(AddressOf Me.MyThread1Work)
Dim MyThread2 As Thread = New Thread(AddressOf Me.MyThread2Work)
ThreadPool.AddRange({MyThread1, MyThread2})
For Each _PT As Thread In ThreadPool : _PT.Start() : Next
Return Await Task.Run(Function()
Dim AllFinished As Integer
While AllFinished < ThreadPool.Count
AllFinished = 0
For Each _T As Thread In ThreadPool
If _T.IsAlive = False Then AllFinished += 1
Next
End While
Console.WriteLine("All Thread Finished")
Return True
End Function)
End Function
Private Sub MyThread1Work(_Obj As Object)
Thread.Sleep(5000)
Console.WriteLine("Thread 1 Finished")
End Sub
Private Sub MyThread2Work(_Obj As Object)
Thread.Sleep(7000)
Console.WriteLine("Thread 2 Finished")
End Sub