Stopping an infinitely looping worker thread

  • Thread starter Thread starter Joel Moore
  • Start date Start date
J

Joel Moore

I've got a class that needs to constantly communicate with an external
device while the app is running. So I've done something similar to the
following:

Imports System.Threading

Public Class Device
Private commThread as Thread

Public Sub New()
commThread = New Thread(AddressOf CommLoop)
End Sub

Public Sub Connect()
commThread.Start()
End Sub

Private Sub CommLoop()
Do While commThread.ThreadState = ThreadState.Running
' Do Stuff
Loop
End Sub

Public Sub Disconnect()
commThread.Abort()
End Sub

End Class

I ignore the ThreadAbortException. From what I can see this works fine.
My question is whether this is the correct way to handle this. Or am I
misusing the Thread.Abort() function by not allowing this thread to exit
normally (i.e. out the end of the CommLoop Sub)? I'd like things to end
as cleanly as possible.

I thought of using a local boolean variable to control the While loop but
I guess I was worried about what could happen if the the thread was busy
somewhere inside the loop and then suddenly the Device object gets
destroyed (which is what's happening after a call to the Disconnect() Sub
since my app is closing at this point). Is this essentially the same as
aborting the thread?

Joel Moore
 
Joel Moore said:
I've got a class that needs to constantly communicate with an external
device while the app is running. So I've done something similar to the
following:

I thought of using a local boolean variable to control the While loop but
I guess I was worried about what could happen if the the thread was busy
somewhere inside the loop and then suddenly the Device object gets
destroyed (which is what's happening after a call to the Disconnect() Sub
since my app is closing at this point). Is this essentially the same as
aborting the thread?

If the app is closing, it's reasonable to use Thread.Abort - although
it would be easier to use a background thread in that case. In
virtually all other cases, I'd go for a boolean variable (with suitable
synchronization). Thread.Abort is dangerous as you can end up with
inconsistent data etc (due to only having done half an operation, for
example).

See
http://www.pobox.com/~skeet/csharp/multithreading.html#worker.threads
for the kind of code I'd use.
 
Back
Top