Call this method from wherever you want (Form.Load, Button.Click...)
The Caller Event Handler/Method doesn't need to be an Async one
ThreadPoolManager()
Define a scope for the List(Of Thread)
that holds the Thread Pool
Dim ThreadPool As List(Of Thread)
ThreadPoolManager()
(a)waits StartThreads()
, which starts all the Threads in the ThreadPool
List. When the Async method returns, then calls 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
The StartThreads()
method initializes all the Threads in ThreadPool with the delegate worker method to invoke when the thread starts
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