Game Development Reference
The user might not be requiring the use of a particular area of the tree, so weak
referencing the tree nodes will allow for the garbage collector to collect unused
portions of the data structure if necessary. If a tree node gets collected, you simply
reload that node and its children when you need them again.
As the user navigates away from a particular region of the tree, you can create some
weak references and release the strong references for the objects in that region. If
memory becomes low enough that the garbage collector requires collection, it will
start to reclaim the weakly referenced tree objects. When the user navigates back
to that same region, the application will try to recreate a strong reference for that
tree. If successful, no memory operations are needed, and if the tree has already
been collected, the application will simply reload that region again.
A prime example of using weak references is a directory browser that loads files
and directories into a hierarchical tree. Keeping a weakly referenced tree in memory
is much more efficient than loading all the data from the hard drive. If a file or
directory node is collected, you can simply reload its contents from that location
on the hard drive.
Once the WeakReference has been instantiated to point at the target object, you
should set the strong reference from the root to null. The garbage collector will not
be able to collect the object if any strong references to it remain.
The proper way to release the weak reference and reobtain a strong reference to the
object is by assigning a root to the Target property of the WeakReference object.
If the property returns null , the object was collected by the GC. Another way to
determine whether the object has been collected is to check the IsAlive property
of the WeakReference object.
The following code shows how to create a weak reference in C#:
MyClass instance = new MyClass ();
WeakReference weakReference = new WeakReference(instance);
instance = null; // Object is no longer rooted
instance = weakReference.Target;
// Object is rooted and can be used again (strong reference)