为什么要明确处理对象? [英] Why to dispose objects explicitly ?

查看:58
本文介绍了为什么要明确处理对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么强烈建议在.net拥有自己的垃圾收集器时自动处理内存释放并在特定时间间隔后运行,从而在finally块中处理所有对象/数据集/数据表。



提前谢谢。

Why its highly recommended to dispose all objects/Datasets/Datatables in finally block when .net have its own Garbage collector which handles memory deallocation automatically and runs after specific interval.

Thanks in advance.

推荐答案

有几个原因。
第一个是因为有些对象使用的资源不是记忆,重要的是尽快返回系统,以便它们可以重复用于其他目的。其中一些可能是您的应用程序本地的,其他可能是您的整个PC的本地。如果它们未被释放,则会发生泄漏,因为每次创建实例时,可用资源的总数会下降,并且系统迟早会耗尽。由于垃圾收集器仅由低内存激活,因此除了显式Disposal之外,没有用于返回这些资源的机制。这些对象包括(但不限于)Graphics上下文,Pens和SqlConnection / SqlCommand对象。



它还有助于释放某些命令保持打开的文件:Bitmap.FromFile例如获取文件的写锁定,该锁定仅在放置位图时释放。因为你不能在任何时候点击GC,所以处理位图是释放它基于写入的文件的唯一方法。



它也有帮助,因为它可以减少内存占用 - 如果你经常分配和Dispose相同大小的对象,可以重复使用相同的内存,并且整个应用程序运行更顺畅,因为从不需要GC(和它总是在最尴尬的时候运行:笑:)
There are a couple of reasons.
The first one is because some objects use resources other than memory, which it is important to return to the system as soon as possible so that they can be reused for other purposes. Some of these may be local to you application, others may be local to your whole PC. If they are not released, then "leaks" occur because the total number of available resources drops each time you create an instance, and sooner or later the system runs out. Since the Garbage Collector is only activated by low memory, there is no mechanism for returning these resources other than explicit Disposal. Such objects include (but are not limited to) Graphics contexts, Pens and SqlConnection / SqlCommand objects.

It also helps to free up files which are held open by some commands: Bitmap.FromFile for example aquires a write lock on the file which is only released when the bitmap is disposed. Since you can''t rrely on teh GC kicking in at any point, Disposing of the bitmap is the only way to free up the file it is based on for writing.

It also helps because it can keep the memory footprint down - if you constantly allocate and Dispose objects of the same size, the same memory can be re-used and your whole app runs more smoothly because the GC is never needed (and it always runs at the most awkward times :laugh: )


当你在对象中使用非托管代码时,你应该明确地处理对象。
You should dispose objects explicitly when they use unmanaged code inside them.


这篇关于为什么要明确处理对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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