需要在使用 TcpClient 的类上实现终结器吗?
我有一个类(例如 MyClass
),它使用(作为私有字段)一个 TcpClient
对象。 MyClass
实现了 IDisposable
,在 Dispose
方法中调用 TcpClient.Close
。
我的问题是 MyClass
是否还应该实现一个终结器来调用 Dispose(bool Dispose)
来释放 TcpClient
非托管资源,以防 MyClass. Dispose
没有被调用代码调用?
谢谢
I have a class (say MyClass
) that uses (has as a private field) a TcpClient
object. MyClass
implements IDisposable
calling TcpClient.Close
in the Dispose
method.
My question is should MyClass
also implement a finalizer to call Dispose(bool Disposing)
to free the TcpClient’s
unmanaged resources in case MyClass.Dispose
is not called by the calling code?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,你不应该。
因为你不应该在终结器中调用其他对象的方法,它可能在你的对象之前被终结。
TcpClient 的终结器将由垃圾收集器调用,所以让他来做吧。
Dispose 中的模式是:
No you shouldn't.
Because you should never call a method on an other object in a finalizer, it could have been finalized before your object.
The finalizer of your TcpClient will be called by the garbage collector, so let him do.
The pattern in Dispose is :
不,你不应该。
来自 此优秀的帖子:
这是我的一次性/最终化模式的参考实现,其中包含解释何时使用的注释:
No you shouldn't.
From this excellent post:
This is my reference implementation of the disposable/finalize pattern with comments explaining when to use what:
不,你不必这样做。 TcpClient 是非托管套接字的包装类,并且以应有的方式对其进行管理。 你所做的就足够了。
No you don't have to. TcpClient is a wrapper class around the unmanaged socket and there for it is managed the way it should be disposed. What you have done is enough.
是的,您应该 - Microsoft 甚至推荐它。
请记住,腰带和吊带代码永远不会让您在凌晨 2:00 被叫到办公室:)
Yes you should - Microsoft even recommends it.
Just remember that belt-and-suspenders code never gets you called into the office at 2:00AM :)