Stopping Thread Blocking on Socket.Receive

  • Thread starter Bruce Vander Werf
  • Start date
B

Bruce Vander Werf

How can I cleanly stop a thread that is currently blocking on
Socket.Receive?

I don't want to use Thread.Abort, because I would like the thread
method to exit cleanly, and the same code must run under the Compact
Framework, which does not support Abort.

Will Socket.Close cause the Receive method to finish, or is there a
better way?

--Bruce
 
W

William Stacey

Just tossing some ideas on the wall. Maybe create your socket (or use
tcpclient/tcpserver) and set a ReceiveTimeout (in ms). Next line would be a
test for a "cancelled" bool in your class. If "cancelled" then break out,
if not, then spin back to socket.receive. Another way may be to use
out-of-band data to the socket as a signal.
 
R

Rich Blum

Bruce Vander Werf said:
How can I cleanly stop a thread that is currently blocking on
Socket.Receive?

I don't want to use Thread.Abort, because I would like the thread
method to exit cleanly, and the same code must run under the Compact
Framework, which does not support Abort.

Will Socket.Close cause the Receive method to finish, or is there a
better way?
Bruce -

If you do not (or can not) abort the thread, the only other
options you have is to either make the Receive() method stop blocking,
use an Asynchronous Receive() method, or use the Poll() or Select()
methods to check the socket before performing the Receive().

There are a couple of ways to make a blocking Receive() method
stop blocking. As suggested by William, you can set the ReceiveTimeout
property of the Socket, forcing the socket to throw an Exception after
a set timeout value. Alternatively, you can create the Socket in the
main Thread and pass that object to the new Thread object. While the
new Thread is blocking on the Receive() method, the main thread can
call the Close() method. This will force the Receive() method to throw
an Exception, which of course you should handle accordingly to cleanly
exit the thread.

Hope this gives you some more ideas to work with. Good luck.

Rich Blum - Author
"C# Network Programming" (Sybex)
http://www.sybex.com/sybexbooks.nsf/Booklist/4176
"Network Performance Open Source Toolkit" (Wiley)
http://www.wiley.com/WileyCDA/WileyTitle/productCd-0471433012.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top