Link to home
Create AccountLog in
Avatar of DavidGreenfield
DavidGreenfieldFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Checking for open Threads when shutting down

Hi there

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

    End Sub

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
            While active_connections
                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
                        Exit For
                    End If
                Next i


            End While

            Log.Write_to_log(Nothing, "Application Shut down")

    End Sub
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account