您是否需要处理对象并将其设置为null,或者当它们超出作用域时,垃圾收集器将清理它们?


当前回答

如果它们实现了IDisposable接口,那么你应该释放它们。垃圾收集器会处理剩下的事情。

EDIT:处理一次性物品时最好使用using命令:

using(var con = new SqlConnection("..")){ ...

其他回答

通常,不需要将字段设置为null。然而,我总是建议丢弃非托管资源。

根据我的经验,我还建议你这样做:

如果不再需要,则取消订阅事件。 如果不再需要,将持有委托或表达式的任何字段设置为空。

我遇到过一些很难发现的问题,这些问题都是由于没有遵循上述建议而直接导致的。

Dispose()是执行此操作的一个好地方,但通常越快越好。

一般来说,如果存在对某个对象的引用,垃圾收集器(GC)可能要多花几代时间才能确定该对象不再使用。在此期间,对象始终保留在内存中。

这可能不是一个问题,直到你发现你的应用程序正在使用比你预期的更多的内存。当发生这种情况时,连接内存分析器来查看哪些对象没有被清理。将引用其他对象的字段设置为null并在处理时清除集合可以真正帮助GC确定可以从内存中删除哪些对象。GC将更快地回收使用的内存,使您的应用程序的内存需求更少,更快。

如果它们实现了IDisposable接口,那么你应该释放它们。垃圾收集器会处理剩下的事情。

EDIT:处理一次性物品时最好使用using命令:

using(var con = new SqlConnection("..")){ ...

当一个对象实现IDisposable时,您应该调用Dispose(在某些情况下,Close将为您调用Dispose)。

您通常不必将对象设置为null,因为GC将知道一个对象将不再使用。

当我将对象设置为空时,有一个例外。当我(从数据库中)检索了很多需要处理的对象,并将它们存储在一个集合(或数组)中。当“工作”完成时,我将对象设置为null,因为GC不知道我已经完成了对它的工作。

例子:

using (var db = GetDatabase()) {
    // Retrieves array of keys
    var keys = db.GetRecords(mySelection); 

    for(int i = 0; i < keys.Length; i++) {
       var record = db.GetRecord(keys[i]);
       record.DoWork();
       keys[i] = null; // GC can dispose of key now
       // The record had gone out of scope automatically, 
       // and does not need any special treatment
    }
} // end using => db.Dispose is called

A little late to the party, but there is one scenario that I don't think has been mentioned here - if class A implements IDisposable, and exposes public properties that are also IDisposable objects, then I think it's good practice for class A not only to dispose of the disposable objects that it has created in its Dispose method, but also to set them to null. The reason for this is that disposing an object and letting it get GCed (because there are no more references to it) are by no means the same thing, although it is pretty definitely a bug if it happens. If a client of Class A does dispose its object of type ClassA, the object still exists. If the client then tries to access one of these public properties (which have also now been disposed) the results can be quite unexpected. If they have been nulled as well as disposed, there will be a null reference exception immediately, which will make the problem easier to diagnose.

在c#中,你永远不需要将对象设置为空。编译器和运行时将负责找出它们何时不再在作用域中。

是的,你应该处理实现IDisposable的对象。