Bnkl
Bnkl

Reputation: 7

Stop a thread that prevents program to close?

I have a really disturbing problem ; when I click the red cross for closing my app , I have an exception here :

    Sub NewThread()
    AddHandler RenderFrameEvent, AddressOf RenderFrame
    Dim lastplay As Boolean = True
    Do
        If lastplay = Not Play Then
            System.Threading.Thread.Sleep(100)
            lastplay = Play
        Else
            If Play = True Then
                KeyState()
                If Me.InvokeRequired Then
                    Me.Invoke(New MethodInvoker(AddressOf NewThread))
                Else
                    RaiseEvent RenderFrameEvent()
                End If
            End If
        End If
        Application.DoEvents()
    Loop
End Sub

I get a System.InvalidOperation exception at

Me.Invoke(New MethodInvoker(AddressOf NewThread))

Because the form is closed , this is quite normal , and then , I do that at FormClosing event :

Trd.Abort '(the thread is named Trd)

And I get an Threading.ThreadAbort exception.

Can anyone tell me how to proprely stop a thread , or how to force the app to kill himself ?

Upvotes: 0

Views: 5630

Answers (1)

Tim Lloyd
Tim Lloyd

Reputation: 38434

Instead of aborting the thread, consider setting a flag which can be checked by your thread and used to exit the loop. In this way the thread will naturally "die".

Upvotes: 2

Related Questions