How to close a blocked socket

The Windows service has an open socket that accepts data (in a separate stream).

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

I'm currently disabling Receive to check if a stop request is waiting. Is there a better approach, rather than waiting for a timeout, to notify the worker thread to stop receiving and go through its shutdown logic?

+4
source share
2 answers

Call Socket.Close . This will call the Socket.Receive method to prevent it from unlocking.

The exception is the IO.IOException, which has a SocketException as an internal exception. The native error code for the internal exception is 10004.

+2
source

An interrupt () call in a thread should force it to exit any blocking operation: http://msdn.microsoft.com/en-us/library/system.threading.thread.interrupt.aspx

Note that this will result in a ThreadInterruptedException (when locked), which you must handle accordingly.

0
source

All Articles