Garbage collector and circular reference

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 17:35:44

The .Net garbage collector can absolutely handle circular references. The very high level view of how the garbage collector works is ...

  • Start with locals, statics and GC pinned objects. None of these can be collected
  • Mark every object which can be reached by traversing the children of these objects
  • Collect every object which is not marked.

This allows for circular references to be collected just fine. So long as none of them are reachable from an object known to be uncollectable then the circular reference is essentially irrelevant.

Note: I realize I've left out many fun details in order to keep this answer simple and direct

Haris Hasan

No, This won't be a problem because GC can handle Circular References

MSDN Says

If a group of objects contain references to each other, but none of these object are referenced directly or indirectly from stack or shared variables, then garbage collection will automatically reclaim the memory.

No that circular reference will not affect the garbage collector, and it will be perfectly able to collect the instance of B.

The garbage collector knows that no-one can reference the instance of B after going out of scope, and consequently, no-one can use the instance of B to indirectly reference A.

Several answers already explained that circular references are not a problem.

As to the weak references - the reason to use them is caching.

When GC walks object dependency trees he ignores weak references. In other words if the only reference to an object is a weak one(s), it will be garbage collected, but if there was no garbage collection between reference creation and your attempt to use, you can still access the object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!