views:

42

answers:

2

A windows service has an open socket that is receiving data (on a separate thread)

In response to the service OnShutdown I would like to signal worker thread to shutdown, but it's currently blocked on the Receive.

At the moment I'm timing out on the Receive to check if there is a stop request pending. Is there a better approach, rather than waiting on the timeout to notify the worker thread to stop receiving and go through its shutdown logic?

A: 

Calling Interrupt() on the thread should make it break out of any blocking operation: http://msdn.microsoft.com/en-us/library/system.threading.thread.interrupt.aspx

Note that this will cause a ThreadInterruptedException (when blocking), which you should handle appropriately.

Bob
that would be great, but it seems that the thread is not blocked by the Socket.Receive in such a way that this interrupt ever gets heard.
Ralph Shillington
+2  A: 

Call Socket.Close. It will cause the Socket.Receive method to throw an exception unblocking it immediately.

Brian Gideon