C#中的垃圾收集 [英] Garbage Collection in C#

查看:109
本文介绍了C#中的垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了对象列表.
我要从对象列表中删除对象,我是否需要通过代码处理这些对象,否则Garbage Collector将负责处理?

I have created list of object.
I am deleting objects from list of objects, do i need to dispose these objects through code or Garbage Collector will take care of it?

推荐答案

这要视情况而定. >
如果对象实现IDisposable,则应在其上调用Dispose(或将其括在using块中),因为该对象包含需要尽快释放的稀缺资源.这里的示例是流,SQL连接,图形对象等.

如果没有,那么只需让GC正常运行-99%的时间,它可以更好地决定什么以及何时处置您将要处置的东西!
It depends.

If the object implements IDisposable, then you should call Dispose on it, (or enclose it in a using block) as it contains scarce resources which need to be released ASAP. Examples here are Streams, SQL Connections, Graphics objects, and so forth.

If it doesn''t, then just let the GC get on with it normally - 99% of the time, it does a better job of deciding what and when to dispose things that you will!


除非您正在使用GDI对象或图像,否则垃圾收集器应该照顾好它.此时,您可能应该从IDisposable派生对象,然后在适用时调用对象的Dispose方法.您的Dispose方法应该处置它创建的所有资源.
The garbage collector should take care of it unless you''re using GDI objects or images. At that point, you should probably derive your objects from IDisposable and then call your object''s Dispose method when applicable. Your Dispose method should dispose of any resources it created.


最好处置掉不再使用的未使用对象.就像您以Connection对象为例一样,当完整的事务完成时,通常在3-Tier体系结构中将其丢弃,因为关闭连接并不总是一件好事,因为它可能会影响应用程序的性能.尽管垃圾收集器会照顾它并在长时间不使用时破坏打开的连接.您必须已经听说过垃圾收集器中的GENERATIONS(请参阅:- http://msdn.microsoft.com/zh-cn/library/ms973837.aspx [ ^ ])

以相同的方式处理不再使用的对象将明显提高性能,而不是让垃圾收集器执行相同的任务.

谢谢
It is always better to dispose off the unused objects which are no longer in use. Like if you take an example of the Connection object, it is generally being disposed off in a 3-Tier architecture when the full transaction gets completed as it is not always good to close a connection as it may have performance issues om the application. Although a Garbage Collector takes care of it and destroys an open connection when it is no longer in use for long time. You must have heard about the GENERATIONS in Garbage collector (refer:-http://msdn.microsoft.com/en-us/library/ms973837.aspx[^])

In the same way disposing the objects which are no longer in use will obviously increases the performance rather then allowing the garbage collector to do the same task.

Thanks


这篇关于C#中的垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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