我想确保我的理解的IDisposable 是正确的,有些事我还是不太清楚的。
的IDisposable 似乎服务于两个目的。
我的困惑来自于确定哪些方案有非托管资源在发挥作用。
假设你正在使用微软提供的的IDisposable -implementing(管理)类(例如,数据库或插座相关的)。
回答你的第一个问题是你不应该需要知道。如果您在使用第三方的code,那么你就其摆布到某一点 - 你不得不相信,它的处置本身正确,当你调用Dispose就可以了。如果你不确定或者你认为有错误,你总是可以尝试使用反射()拆开它(如果可能的话),并检查了它在做什么。
您应该很少,如果以往任何时候都需要的,如果你使用的.Net 2.0或以上,以实现一个终结你的类。终结开销添加到您的类,而且通常没有提供更多的功能,那么你需要用刚刚实施处置。我想强烈推荐一个很好的概述关于正确处理访问这篇文章 。在你的情况,你想叫 instanceofMSSuppliedClass.Dispose()在自己的Dispose()方法。
最后,在对象上调用Dispose()是很好的做法,因为它显式地让GC知道你的资源完成,并允许用户立即清除它的能力,并间接文件code。通过让其他程序员知道该对象在该点完成的资源。但是,即使你忘记了显式调用它,它会发生,最终当对象是无根(净毕竟是一个管理的平台)。如果你的对象的非托管资源,将需要清理隐(即有机会的话,消费者可以忘记把它清理干净,并认为这将是有问题的)终结只应实施。
I'm trying to make sure that my understanding of IDisposable is correct and there's something I'm still not quite sure on.
IDisposable seems to serve two purpose.
My confusion comes from identifying which scenarios have "unmanaged resources" in play.
Say you are using a Microsoft-supplied IDisposable-implementing (managed) class (say, database or socket-related).
解决方案
The answer to your first question is "you shouldn't need to know". If you're using third party code, then you are its mercy to some point - you'd have to trust that it's disposing of itself properly when you call Dispose on it. If you're unsure or you think there's a bug, you could always try using Reflector() to disassemble it (if possible) and check out what it's doing.
You should rarely, if ever, need to implement a finalizer for your classes if you're using .Net 2.0 or above. Finalizers add overhead to your class, and usually provide no more functionality then you'd need with just implementing Dispose. I would highly recommend visiting this article for a good overview on disposing properly. In your case, you would want to call instanceofMSSuppliedClass.Dispose() in your own Dispose() method.
Ultimately, calling Dispose() on an object is good practice, because it explictly lets the GC know that you're done with the resource and allows the user the ability to clean it up immediately, and indirectly documents the code by letting other programmers know that the object is done with the resources at that point. But even if you forget to call it explicitly, it will happen eventually when the object is unrooted (.Net is a managed platform after all). Finalizers should only be implemented if your object has unmanaged resources that will need implicit cleanup (i.e. there is a chance the consumer can forget to clean it up, and that this will be problematic).
更多推荐
IDisposable接口,终结和非托管资源的定义
发布评论