【问题标题】:Does one need to close both NetworkStream and TcpClient, or just TcpClient?是否需要同时关闭 NetworkStream 和 TcpClient,或者只关闭 TcpClient?
【发布时间】:2017-05-15 07:11:53
【问题描述】:

我正在阅读 the documentation on TcpClient.Close() 并注意到这一点:

调用此方法最终会导致关联的 Socket 关闭,并且还会关闭关联的用于发送和接收数据的 NetworkStream(如果已创建)。

所以,如果我错了,请纠正我,但这表示如果有人在 TcpClient 上调用 Close()NetworkStream 也将被关闭。

那么为什么在代码示例的末尾都调用了Close()

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

只打电话tcpClient.Close();也可以吗?

【问题讨论】:

  • 是的,没有必要。在该示例中使用 tcpClient.Close() 也不是必需的,程序在此之后立即终止:)
  • 在 .NET 3.0 之前,TcpClient 和底层 NetworkStream 都必须显式关闭。从 .NET 3.0 开始,底层 NetworkStream 在关闭 TcpClient 时关闭。 TcpClient 上的 Close() 和 Dispose() 是等效的,Close() 添加了一些内部日志记录。

标签: c# dispose tcpclient networkstream


【解决方案1】:

回答这个问题,因为没有其他人这样做,所以我可以接受答案。

根据 Hans 的说法,调用 NetworkStream.Close() 是不必要的,因为 TcpClient.Close() 会关闭其底层 NetworkStream。

【讨论】:

  • 这个答案不正确。见薇薇安的回答。如那里所述,doc for GetStream 状态 You must close the NetworkStream when you are through sending and receiving data. Closing TcpClient does not release the NetworkStream.
  • 但是,doc for Close 声明 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. 我怀疑 GetStream 文档已过时 - 该注释自 .NET 2.0 以来一直存在(当时它仍然是一个问题)。
  • 我也有同样的问题,发现这个帖子,参考源码确认TcpClient.Close也调用了NetworkStream的Close,所以这个答案是正确的。 referencesource.microsoft.com/#System/net/System/Net/Sockets/…
【解决方案2】:

NetworkStream 和 TcpClient 实现 IDisposable。所以我认为最好的做法是将它打包到一个 using 块中,这样你就不需要手动关闭或处置它。

【讨论】:

    【解决方案3】:

    关闭客户端并不会关闭流,它在 GetStream 方法的文档中。 作为参考,请查看此讨论:How to properly and completely close/reset a TcpClient connection?

    【讨论】:

    • As Sam writes here,该注释已过期。它曾经是必要的,但从 .NET 3.0 开始不再是必要的。
    【解决方案4】:

    你应该只做“TcpClient.Close()”
    或者,如果必须,请输入两者

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      相关资源
      最近更新 更多