I have an application that is connecting to some network server (tcp) and is connected using a network stream:
if (!SSL)
{
_networkStream = new System.Net.Sockets.TcpClient(Server, Port).GetStream();
_StreamWriter = new System.IO.StreamWriter(_networkStream);
_StreamReader = new System.IO.StreamReader(_networkStream, Encoding.UTF8);
}
if (SSL)
{
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Server, Port);
_networkSsl = new System.Net.Security.SslStream(client.GetStream(), false,
new System.Net.Security.RemoteCertificateValidationCallback(Protocol.ValidateServerCertificate), null);
_networkSsl.AuthenticateAsClient(Server);
_StreamWriter = new System.IO.StreamWriter(_networkSsl);
_StreamReader = new System.IO.StreamReader(_networkSsl, Encoding.UTF8);
}
///// since now I working with both reader and writer globally in multiple threads
I am using reader and writer asynchronously (in 2 threads) and I need to have both of these streams globally available (they are defined as public references on class level), so I don't know if using statement can be used here.
How should I properly close this connection? All objects (NetworkStream, stream writer and reader) have the Close() method. Should I call it for all of them? Or only 1 of them? Is there any need to release some resources?
Put them in a using block. It will close and dispose of each stream appropriately after the operation has been completed.
using (StreamReader reader = new StreamReader(_networkStream, Encoding.UTF8))
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With