垃圾收集:是否有必要在Dispose方法设置大对象为空?有必要、为空、对象、垃圾

2023-09-02 21:48:04 作者:5.深知我心.

是否有必要设置大对象实施时,的Dispose()的方法?

Is it necessary to set large objects to null when implementing a Dispose() method?

推荐答案

不一般。

在垃圾收集器查找根对象,以及循环依赖并不prevent集合,如果没有对象是植根。

The garbage collector looks for rooted objects, and circular dependencies don't prevent collection if neither object is rooted.

有一个警告:如果对象A引用对象B,并且对象B被布置,您可能要清理的关系,否则你可以用一个防漏结束。这个表面最常见的地方是在事件处理程序(从A-> B的基准是一个B控制,因为它订阅上的一个事件)。在这种情况下,如果A仍然根,B不能被即使它被布置收集

There is a caveat: if object A has a reference to object B, and object B is being disposed, you may want to clean up that relationship or else you could end up with a leak. The most common place this surfaces is in event handlers (the reference from A->B is one that B controls, because it subscribed to an event on A). In this case, if A is still rooted, B cannot be collected even though it's been disposed.