c# - 如何正确关闭网络流连接?

标签 c# networking

我有一个连接到某个网络服务器 (tcp) 并使用网络流连接的应用程序:

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

我正在异步使用读取器和写入器(在 2 个线程中),我需要让这两个流都全局可用(它们在类级别上被定义为公共(public)引用),所以我不知道是否使用 声明可以在这里使用。

我应该如何正确关闭此连接?所有对象(NetworkStream、流写入器和读取器)都有 Close() 方法。我应该为他们所有人打电话吗?还是只有其中之一?是否需要释放一些资源?

最佳答案

将它们放在 using block 中。操作完成后,它将关闭并适本地处理每个流。

using (StreamReader reader = new StreamReader(_networkStream, Encoding.UTF8)) 
{

}

关于c# - 如何正确关闭网络流连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16538493/

相关文章:

c# - 在另一个窗口中设置编辑控件的文本

linux - 在 Linux 中的临时网络上托管 Web 应用程序

linux - Linux 中的网络命名空间是什么?

testing - Symbian Series 60 第 5 版设备上是否有 HOSTS 文件?

java - 使用 Square 的 Retrofit Client,是否可以取消正在进行的请求?如果有怎么办?

macos - 如何将docker-machine创建的VM绑定(bind)到OSX IP地址?

c# - RegisterForContextMenu 似乎没有效果

c# - 调试符号未加载到针对 .NET Framework 的 .NET 标准项目中

c# - WebBrowser 在特定网页上停止响应,但 IE 没有

c# - 使用自动完成和 Ajax 进行搜索