Note that there are some explanatory texts on larger screens.

plurals
  1. POGarbage Collection - Is it always safe to access objects via strong references?
    text
    copied!<p>My understanding is that when the GC finds a sub-graph of objects that are no longer accessible (via strong references) from the main graph, it will collect them up and reclaim the memory. My question is concerning the order in which inaccessible objects are deleted. Does this occur as an atomic operation? Are all of the inaccessible objects finalized at once, or does the GC finalize each object one-by-one while the application is still executing? If the objects are finalized one-by-one, is there a particular order that is followed?</p> <p>If I have an object A that holds a weak reference to object B, then it is clear that A must check if B is still alive before invoking any of B’s instance methods. Now suppose B holds a strong reference to another object C. If B is still alive, am I always guaranteed that C will also still be alive? Is there any possibility that the GC might have marked both B &amp; C for collection, but C is finalized before B? </p> <p>My guess is that it will always be safe to access C from B (since this is a strong reference). But I would like to confirm this assumption, because if I am wrong I could introduce a very intermittent hard-to-track-down bug. </p> <pre><code>public class ClassA { private readonly WeakReference objBWeakRef; public ClassA(ClassB objB) { objBWeakRef = new WeakReference(objB); } public void DoSomething() { // The null check is required because objB // may have been cleaned-up by the GC var objBStrongRef = (ClassB) objBWeakRef.Target; if (objBStrongRef != null) { objBStrongRef.DoSomething(); } } } public class ClassB { private readonly ClassC objCStrongRef; public ClassB(ClassC objC) { objCStrongRef = objC; } public void DoSomething() { // Do I also need to do some kind of checking here? // Is it possible that objC has been collected, but // the GC has not yet gotten around to collecting objB? objCStrongRef.DoSomething(); } } public class ClassC { public void DoSomething() { // do something here... if object is still alive. } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload