I have a theory that the CLR garbage collection mechanism means that I can get away with circular references in my object hierarchy without creating deadlocks for teardown and garbage collection. Is this a safe assumption to make? (Target language VB.NET)
-
See here for a similar question with a very good accepted answer http://stackoverflow.com/questions/400706/circular-references-cause-memory-leak – Martin Harris Feb 03 '10 at 11:49
-
@David: AZ said it does _not use reference counting. – Johannes Rudolph Feb 03 '10 at 11:56
-
@Johannes: that was a typo in my comment, I meant the question (not the answer) the initial question was whether the use of reference counting in CLR made cycles unsafe. The question (not the answer by AZ) was wrong about how the CLR does GC. – David Rodríguez - dribeas Feb 03 '10 at 12:38
2 Answers
The .NET garbage collector is a generational mark and sweep collector. It does not use reference counting. So yes, it's safe to have circular references. Language is irrelevant

- 7,907
- 6
- 35
- 53
-
1Just be very careful to avoid passing a reference to a static and also remember that delegates will count as a reference to the object they are implemented on. very easy to keep things alive with things like a static event handler list. – morechilli Feb 03 '10 at 12:59
As per this article: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5109829.html
Circular reference is a problem that occurs when there are two objects that refer to each other. Let's say you have Class A that refers to Class B. If Class B also refers to Class A, then we have a circular reference. This happens in many situations. A typical example for this is a parent-child relationship between objects, where the child interacts with the parent object and also holds a reference to the parent object. This could lead to objects that would not get cleaned up until the application was shut down. The .NET way of garbage collection solves the problem of circular reference because the garbage collector is able to clean up any object that is reachable from the root.
EDIT:
Judging from this post: http://blogs.msdn.com/abhinaba/archive/2009/01/27/back-to-basics-reference-counting-garbage-collection.aspx it seems that .Net's garbage collection is not based on reference counting for garbage collection.
Another article worth reading (explains Garbage collection in detail) is this one: http://www.simple-talk.com/dotnet/.net-framework/understanding-garbage-collection-in-.net/