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?
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.
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.
精彩评论