We help IT Professionals succeed at work.

Checking for open Threads when shutting down

DavidGreenfield
on
204 Views
Last Modified: 2010-04-23
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
            add_to_thread_handler(t)
            t.Start()


    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

                System.Threading.Thread.Sleep(3000)

            End While

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

    End Sub
Comment
Watch Question

High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.