I have a windows service which runs a separate background thread. Inside the thread it starts a TCP server which listens to clients using TcpListener.
I’d like to know how I can close the service down gracefully when there is a blocking read like so:
listener.AcceptTcpClient();
I’ve found that apparently a windows service can abort any other threads as long as they are set-up as background threads, but what if one of the threads is blocking? Does this make a difference and if so, what is the best way to handle this situation?
Best way will be to call
listener.Close()on service’s stopping event. It will abort blocking call withSocketException.State of the thread (blocked or running) does not affect the fact that thread is background. So if you call
listener.AcceptTcpClient()from a background thread it will still be aborted when service stops,