本文介绍了为什么垃圾收集器不知道什么时候引用彼此的对象真的是孤儿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在像Java或C#这样的托管语言中,有一种叫做垃圾收集器的东西,每隔一段时间就会检查是否有任何对象实例不再被引用,因此完全孤立,并且清除然后内存不足。但是,如果两个对象没有被程序中的任何变量引用,但是彼此相互引用(如事件订阅),垃圾收集器将看到该引用并且不清除内存中的对象。



这是为什么?为什么垃圾收集器无法弄清楚这两个对象都不能被正在运行的程序的任何活动部分引用并处理它们。

解决方案

你的推定是不正确的。如果GC'看到'(见下文)2个或更多对象的循环引用(在'Mark'阶段期间),但没有被任何其他对象或永久GC句柄(强引用)引用,这些对象将被收集(在'清扫'阶段)。

深入了解CLR垃圾收集器可以在和。



注意:事实上,GC甚至在标记期间看不到这些类型的对象阶段,因为它们无法访问,因此在扫描期间收集。


I understand that in a managed language like Java or C# there is this thing called a garbage collector that every once in a while checks to see if there are any object instances that are no longer referenced, and thus are completely orphaned, and clears then out of memory. But if two objects are not referenced by any variable in a program, but reference each other (like an event subscription), the garbage collector will see this reference and not clear the objects from memory.

Why is this? Why can't the garbage collector figure out that neither of the objects can be reference by any active part of the running program and dispose them.

解决方案

Your presumption is incorrect. If the GC 'sees' (see below) a cyclic reference of 2 or more objects (during the 'Mark' phase) but are not referenced by any other objects or permanent GC handles (strong references), those objects will be collected (during the 'Sweep' phase).

An in-depth look at the CLR garbage collector can be found in this MSDN article and in this blog post.

Note: In fact, the GC doesn't even 'see' these types of objects during the mark phase since they are unreachable, and hence get collected during a sweep.

这篇关于为什么垃圾收集器不知道什么时候引用彼此的对象真的是孤儿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 19:44