Checking for open Threads when shutting down
Posted on 2007-10-05
I have an application that creates lots of threads. On shutting down I need to delay shut down until all the threads have closed. For most of the threads thread_handler(i).IsAlive seems to work. But the last 4 threads I use to disconnect are still alive and don't ever seem to close! As a result my code goes into a loop.
If I run call disconnection on its own outside from closing this works without problem. and I get
The thread 0xf0c has exited with code 0 (0x0). x 4
Its only when its in form closing - I never seem to get the above message and the threads never close.
Can anyone help me??
code is below:
Public thread_handler() As Thread 'keep track of all the threads
Dim t As New Thread(AddressOf c.Connect) 'Declare a thread to run connect actions on the connection
Private Sub add_to_thread_handler(ByRef t As Thread)
Dim count As New Integer
If thread_handler Is Nothing Then count = 0 Else count = UBound(thread_handler) + 1
ReDim Preserve thread_handler(count)
thread_handler(count) = t 'add thread to thread handler
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
call disconnection 'this creates 4 new threads (each thread takes about 6 seconds)
Dim active_connections As Boolean = True
For i As Integer = 0 To UBound(thread_handler)
active_connections = False
'if there is an active connection fall out of loop
If thread_handler(i).IsAlive Then
active_connections = True
Log.Write_to_log(Nothing, "Application Shut down")