wrtsvkrfm wrtsvkrfm - 3 years ago 116
Vb.net Question

Thread quitting in middle of Method?

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

Answer Source

Visual Studio's debugger will switch from thread to thread if the breakpoints are there since they run concurrently. I believe that explains this part of your question "so execution left the method and continued in the external thread completion-monitoring code".

I speculate your problem is that you exit the for loop if a single thread is stopped, yet you are iterating through a list of threads. REMOVE this code and I believe your issue will be resolved:

If t.ThreadState = Threading.ThreadState.Stopped = True Then Exit For

Finally, here is a good MSDN link that describes different multithreading debugging techniques using Visual Studio.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download