0

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 ?

Bnkl
  • 7
  • 1
  • 5
  • 1
    Set the [IsBackground](http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx) property to true on background threads, that way those threads will not keep your program from exiting, the runtime will automatically terminate those threads instead. – Rolf Bjarne Kvinge Dec 17 '12 at 10:44
  • Hmmm ... The thread is already set as background :) – Bnkl Dec 17 '12 at 16:37

1 Answers1

2

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".

Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130
  • You mean that , in my case , I set Play to false ? Because it doesn't works and I still get an InvalidOperation exception – Bnkl Dec 16 '12 at 12:43
  • In your current logic I can't see where `lastplay` will ever be set to false, but anyway I would introduce another flag such as `ExitPlayBack`. I think you need to be able to represent `Play`[True|False] as well as a flag to exit the loop completely. – Tim Lloyd Dec 16 '12 at 12:46
  • Actually , to solve this , I've done a `If ExitThread then Exit Do` , And I just have to Set ExitThread as true . Thanks to @Chibacity – Bnkl Dec 16 '12 at 14:44
  • Yes it is generally not a good idea to abort threads (e.g. http://stackoverflow.com/questions/2180033/thread-abort-in-net). Always best to let threads exit naturally. – Tim Lloyd Dec 16 '12 at 14:45