I’m looking through some code which hasn’t been written by myself and I’m trying to understand what is causing the application to crash.
I think that possibly it comes down to how it disposes of resources and manages threads.
A main parent thread creates a new Application layer client (TCPMonitor) which then creates another class which handles the TCP socket comms (TCPListen). This class spawns a new thread loop that creates a new TCP socket client, a read network stream on that socket, and then calls a synchronous blocking Read().
However, if a network error connection occurs, the exception is caught in the TCPListen thread loop and an event raised back to the owning class TCPMonitor. TCPMonitor then checks to see if it holds an active TCPListen instance and if so it calls Dispose() and sets the instance to Null.
At this point the TCPListen Read() will still be in its blocking call surely? If that is the case, how do I ensure that calling the Dispose from the parent thread will break the child thread out of the blocking call and properly dispose of the stream and socket?
Shutdown the socket for input. That will unblock the read and cause it to get an EOS indication, whatever form that takes in the API. As you are on Windows, it will also cause the other end to get a connection rest if it keeps sending. (This behaviour is platform-dependent.)