busarider29
busarider29

Reputation: 305

Killing a thread completely in Multithreaded application

Can someone show/tell me where I'm steering wrong with this? I am running a second thread in my application where all it does is read values from registers in a motion controller and then constantly updates those values to the appropriate fields on my UI every 100ms. When I disconnect the controller (ie...Ethernet cable disconnected, so lost comms), I want to destroy/terminate the thread (thread1) completely. When I reconnect the Ethernet cable, I click a button on my UI to reestablish comms to the controller, and execute Runthread() Sub. That is when I want to recreate the thread and start it. However, when debugging this part of the code, it appears that the thread (thread1) is never destroyed even though I have verified that the code does get to that line (Case 1) and execute it. After comms is re-established, the code goes right to Case 3 and starts thread1, where I would expect it to jump to Case 2 and recreate the thread.

Public Class frmMain
    Private RMC As RMCLink
    Public thread1 As System.Threading.Thread = New System.Threading.Thread(AddressOf ReadRegisters)
    Private Sub RunThread()
        Dim conditions As Integer
        If RMC.IsConnected(PingType.Ping) = False And thread1 IsNot Nothing Then
            conditions = 1
        ElseIf RMC.IsConnected(PingType.Ping) = True And thread1 Is Nothing Then
            conditions = 2
        ElseIf RMC.IsConnected(PingType.Ping) = True And thread1 IsNot Nothing Then
            conditions = 3
        End If

        Select Case conditions
            Case 1
                Thread.Sleep(100)
                thread1.Abort()
            Case 2
                Dim thread1 As System.Threading.Thread = New System.Threading.Thread(AddressOf ReadRegisters)
                thread1.Start()
            Case 3
                thread1.Start()
        End Select
    End Sub

Upvotes: 0

Views: 5861

Answers (1)

Tony Hinkle
Tony Hinkle

Reputation: 4742

The documentation (https://msdn.microsoft.com/en-us/library/system.threading.thread.abort(v=vs.110).aspx) states that it usually terminates the thread, but as you've found this doesn't always happen.

One way to accomplish this (I'm sure there are others), is to create a public PleaseDie property that your thread's subroutine(s) check periodically, and if that property is set to True, then exit the subroutines within the thread. Before the thread is started, you'll of course have to reset PleaseDie to False.

Upvotes: 1

Related Questions