为什么我们需要一些处置对象上()方法?为什么没有垃圾收集器做这个工作? [英] Why do we need Dispose() method on some object? Why doesn't the garbage collector do this work?

查看:181
本文介绍了为什么我们需要一些处置对象上()方法?为什么没有垃圾收集器做这个工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在的问题是:为什么我们需要调用的Dispose()对某些对象?为什么没有垃圾收集器收集的对象,当它超出范围?我试图理解为什么有人这样实现的原因。我的意思是,那岂不是更容易,如果的Dispose()当垃圾收集器收集范围外的对象被调用。

The question is: why do we need to call Dispose() on some objects? Why doesn't the garbage collector collect the object when it goes out of scope? I am trying to understand the reason why it was implemented like that. I mean, wouldn't it be easier if Dispose() was called when the garbage collector collected out of scope objects.

推荐答案

垃圾回收器的不确定性 - 它在收集对象的某一点的后,他们不再被引用,但它不能保证在发生及时。这个拥有引用计数的各种好处,包括允许循环依赖,而不是递增和递减计数器所有的地方的性能优势。

The garbage collector is non-deterministic - it collects objects at some point after they're no longer referenced, but it's not guaranteed to happen in a timely fashion. This has various benefits over reference counting, including allowing cyclic dependencies and the performance benefit of not incrementing and decrementing counters all over the place.

然而,这并不意味着资源其中的及时进行清理(比如数据库连接,文件处理等功能 - 内存以外几乎所有的东西),你仍然需要明确处置的资源。在使用语句使虽然这很容易。

However, it does mean that for resources which should be cleaned up in a timely manner (such as database connections, file handles etc - almost anything other than memory) you still need to explicitly dispose of the resource. The using statement makes this pretty easy though.

这篇关于为什么我们需要一些处置对象上()方法?为什么没有垃圾收集器做这个工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆