Search code examples
disposetcpclientnetworkstream

Close TcpClient and its underlying NetworkStream


I am now developing a server/client application using TCP protocol for its communication protocol. I have two questions about TcpClient and its underlying NetworkStream. I was goolging, but could not find a clear answer

(1) If I close TcpClient using TcpClient.Close() method, is the underlying NetworkStream will also be closed automatically? For .Net framework 4.5 here (http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx) says that "You must close the NetworkStream when you are through sending and receiving data. Closing TcpClient does not release the NetworkStream." However, also for .Net framework 4.5 here ("http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.close(v=vs.110).aspx") says that "Calling this method (TcpClient.Close) will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created." I am very confused now.

(2) If I keep my TcpClient open and connected, but I close/dispose the underlying NetworkStream obtained by calling TcpClient.GetStream, can I get such a stream again by calling GetStream method?

Thank you for your inputs!


Solution

  • The general rule is that you should try hard to dispose of any disposable resources, except if it is well known that doing so has no benefit (the best example would be Task).

    If you see a significant reason why you would like to not dispose of the TcpClient or the paired NetworkStream: Reflector shows that GetStream transfers ownership of the underlying socket to the NetworkStream. But disposing either of the two will shutdown and close the socket.

    You can safely dispose of just one of the two because the socket is the only unmanaged resource held.

    This means that your first quote is a documentation bug.

    What I just said is undocumented knowledge derived from decompiling the source code. I'd feel pretty safe relying on that knowledge because the behavior has been like this for 10 years and can never be changed for compatibility reasons. Microsoft tries very hard to not break user code.