Ralph Shillington
Ralph Shillington

Reputation: 21098

How to close a blocked socket

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?

Upvotes: 4

Views: 580

Answers (2)

Brian Gideon
Brian Gideon

Reputation: 48949

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

The exception is an IO.IOException, that has an SocketException as an inner exception. The native error code of the inner exception is 10004.

Upvotes: 2

Bob
Bob

Reputation: 3351

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.

Upvotes: 0

Related Questions