Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does one need to close both NetworkStream and TcpClient, or just TcpClient?

I'm reading the documentation on TcpClient.Close() and noticed this:

Calling this method 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.

So, correct me if I'm wrong but this says that if one calls Close() on the TcpClient that the NetworkStream will also be closed.

So then why at the end of the code example are both Close() called?

networkStream.Close();
tcpClient.Close();

Would it be just as fine to only call tcpClient.Close();?

like image 410
Ryan Peschel Avatar asked Sep 30 '11 23:09

Ryan Peschel


3 Answers

Responding to this question since no one else did so that I may accept an answer.

According to Hans, calling NetworkStream.Close() is unnecessary because TcpClient.Close() closes its underlying NetworkStream.

like image 83
Ryan Peschel Avatar answered Oct 23 '22 09:10

Ryan Peschel


NetworkStream and TcpClient implement IDisposable. So best practise in my opinion is to pack it into a using block, so you never need to close or dispose it manually.

like image 39
NickD Avatar answered Oct 23 '22 07:10

NickD


Closing the client does not close the stream, it's in the doc of the GetStream method. For the reference, have a look to this discussion : How to properly and completely close/reset a TcpClient connection?

like image 40
Vivien Ruiz Avatar answered Oct 23 '22 07:10

Vivien Ruiz