I cannot implement workerthreads since there are already too many classes developed with their own threads which call upon methods. It seems that, if there is any looping code to monitor completion of running threads, the only way to allow the started threads to complete their work is to feed them "sleep" time. Otherwise, sitting on a WaitOne outside of a thread or attempting anything using a Do-While loop to wait for threads to complete is difficult to successfully perform.
Below is my code which monitors completion of threads in a ThreadList, which works most of the time, however, I traced through breakpoints in a running Method (which was fired via a thread in an instantiated class), and the code simply determined that the thread completed, so execution left the method and continued in the external thread completion-monitoring code.
Do you see any problems in the code below which would cause a thread to falsely signal it was completed, causing execution to leave the For loop below? Also, will an overabundance of thread sleep time be added to memory using this approach?
startagain:
For Each t In threadList
If t.ThreadState = Threading.ThreadState.Stopped = False Then
wait(1)
GoTo startagain
End If
If t.ThreadState = Threading.ThreadState.Stopped = True Then Exit For
Next
Private Sub wait(ByVal seconds As Integer)
For i As Integer = 0 To seconds * 100
System.Threading.Thread.Sleep(10)
Application.DoEvents()
Next
End Sub
Thread.Sleep(1000 * seconds)
instead of that really unnecessary loop? Also, you should NEVER useApplication.DoEvents()
like this! It is very bad practice! Please see: Keeping your UI Responsive and the Dangers of Application.DoEvents. – Visual Vincent Sep 30 '17 at 7:29