TcpClient资源处置
假设我有一个通过 TcpClient.GetStream()
生成的 Stream
。如果我stream.Dispose()
,是否有必要处置创建Stream
的TcpClient
?
Say I have a Stream
produced via TcpClient.GetStream()
. If I stream.Dispose()
, is it necessary to dispose of the TcpClient
that created the Stream
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看ILSpy中
TcpClient.GetStream
和TcpClient.Dispose
的实现,我同意如果你调用Dispose()
你不应该出现资源泄漏code> 在流上,但不在客户端上。然而,我不相信这是一个好主意。
我想问为什么要避免在
TcpClient
实例上调用Dispose()
。TcpClient
实现IDisposable
这一事实隐含的契约是,当不再需要实例时,应该调用Dispose()
。如果你违反了这个契约:
TcpClient
的实现在未来版本中发生变化怎么办?Looking at the implementations of
TcpClient.GetStream
andTcpClient.Dispose
in ILSpy, I agree that you should not have a resource leak if you callDispose()
on the stream but not on the client.However, I am not convinced it is a good idea anyway.
I'd ask why you want to avoid calling
Dispose()
on the instance ofTcpClient
. The contract implied by the fact thatTcpClient
implementsIDisposable
is thatDispose()
should be called when an instance is no longer required.If you break this contract:
TcpClient
changes in future versions?好的。我自己拿出 Reflector 来检查一下。如果您在
TcpClient
上调用GetStream
,它会将成员 m_DataStream 初始化为非空值。TcpClient 的 dispose 方法的主体如下所示:
因此,如果我自己处置流,我将执行与 TcpClient 执行的处置相同的处置。
据我所知,如果我处置流,则无需处置 TcpClient。
有人不同意吗?
OK. I got out Reflector to check this myself. If you call
GetStream
onTcpClient
it initializes a member m_DataStream to a non-null value.The body of the dispose method of TcpClient looks something like this:
Therefore, if I dispose the stream myself, I'm performing the same disposal as performed by TcpClient.
So as far as I can tell, if I dispose the stream it's unneccessary to dispose the TcpClient.
Does anyone disagree?