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


当前回答

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.

其他回答

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

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

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

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

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

正如其他人所说,如果类实现了IDisposable,则肯定需要调用Dispose。我在这个问题上的立场相当坚定。例如,有些人可能会声称在DataSet上调用Dispose是没有意义的,因为他们分解了DataSet,发现它没有做任何有意义的事情。但是,我认为这种说法有很多谬误。

阅读这篇文章,你会看到一场由受人尊敬的人就这个问题展开的有趣辩论。然后阅读我的推理,为什么我认为杰弗里·里希特站在错误的阵营。

现在,关于是否应该将引用设置为null。答案是否定的。让我用下面的代码来说明我的观点。

public static void Main()
{
  Object a = new Object();
  Console.WriteLine("object created");
  DoSomething(a);
  Console.WriteLine("object used");
  a = null;
  Console.WriteLine("reference set to null");
}

So when do you think the object referenced by a is eligible for collection? If you said after the call to a = null then you are wrong. If you said after the Main method completes then you are also wrong. The correct answer is that it is eligible for collection sometime during the call to DoSomething. That is right. It is eligible before the reference is set to null and perhaps even before the call to DoSomething completes. That is because the JIT compiler can recognize when object references are no longer dereferenced even if they are still rooted.

如果对象实现了IDisposable,那么是的,你应该释放它。对象可能挂在本地资源(文件句柄、操作系统对象)上,否则这些资源可能不会立即释放。这可能导致资源短缺、文件锁定问题和其他本来可以避免的微妙错误。

参见在MSDN上实现一个Dispose方法。

总是调用dispose。不值得冒这个险。大型托管企业应用程序应该受到尊重。不能做任何假设,否则它会反过来咬你一口。

别听她的。

很多对象实际上并没有实现IDisposable,所以你不必担心它们。如果他们真的超出了范围,他们将自动被释放。此外,我从来没有遇到过必须将某些内容设置为null的情况。

可能发生的一件事是,很多物体都可以保持打开状态。这将极大地增加应用程序的内存使用。有时很难判断这究竟是内存泄漏,还是您的应用程序只是在做很多事情。

内存配置文件工具可以帮助解决这类问题,但它可能很棘手。

此外,始终取消对不需要的事件的订阅。还要注意WPF绑定和控件。不常见的情况,但我遇到了这样的情况,我有一个WPF控件被绑定到一个底层对象。底层对象很大,占用了大量内存。WPF控件正在被一个新的实例所取代,而旧的实例由于某种原因仍然存在。这导致了一个大的内存泄漏。

在后台,代码写得很糟糕,但关键是你要确保没有使用的东西超出了范围。这需要很长时间才能用内存分析器找到,因为很难知道内存中的哪些东西是有效的,哪些不应该在那里。