Killing background thread when in blocking call

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi:

I have a class that needs to request/receive updates from a server over a
network connection for the entire life of the application. I use a
background worker thread to do this, and then send updates to the main thread
using events. This works great.

My issue is that when a user wants to terminate the application, the thread
could be (will be) in any number of blocking calls, for example
BinaryReader.ReadByte. Almost all of what my background thread does is pull
data from the server via a TcpClient > Stream > BinaryReader.

I've done lots of reading on the topic, and everyone seems to say that I
sould use a ManualResetEvent and have the thread check periodically that this
event hasn't been Set. I do this now.

The problem is that even though I check to see if the event has been set,
the next line of code will start a blocking read.

I don't want to use Thread.Abort, and I don't want to switch to non-blocking
calls on the socket.

What am I missing?

Thanks.

Dave

P.S. Why not use a bool instead of a ManualResetEvent? Are value types not
thread safe?
 
Hi,

IMO, if you are going to use a blocking read, you should... Not, really.
You still can use the blocking read, but do it in a loop (like the following
pseudo-code):

Do Until ExitFlagSet
If MyReader.DataAvailable Then
DoMyReadCode
Else
Thread.Sleep (1) 'or some longer Sleep
End If
Loop

Then use the ExitFlagSet boolean to exit the thread. This way, the code
never really blocks -- it always is in a state where it may exit cleanly.
I've found this to be the simplest structure... And, so far, it has worked
well for me.

Dick

--
Richard Grier (Microsoft Visual Basic MVP)

See www.hardandsoftware.net for contact information.

Author of Visual Basic Programmer's Guide to Serial Communications, 4th
Edition ISBN 1-890422-28-2 (391 pages) published July 2004. See
www.mabry.com/vbpgser4 to order.
 
dhumphrey said:
What am I missing?

I tend to call Socket.ShutDown (followed of course by Socket.Close), and if
a blocking operation on the Socket is happening at the time then it's
interrupted and a SocketException is thrown.
 
Back
Top