Game Development Reference
As discussed earlier, an object cannot be collected if there is a root pointing to it
(strong reference). However, this is not the only way of referencing an instantiat-
ed object. The GC also supports the notion of weak references. A weak reference
to an object allows the garbage collector to perform collection if needed, but also
allows the application to use the object. The first thing that probably popped into
your head was having a NullReferenceException thrown when the application
attempts to access an object after being collected; using weak references is an issue
It is important to note that an application must obtain a strong reference to access a weakly refer-
enced object. If this strong reference has been obtained before the garbage collector runs, the
object cannot be collected.
The WeakReference object offers two constructors:
WeakReference(object target, bool trackResurrection);
The target parameter specifies which object a weak reference should be obtained
for, and the trackResurrection parameter specifies whether or not the
WeakReference should track the target after its Finalize method has been called; the
trackResurrection parameter defaults to false with the first constructor.
A WeakReference that does not track resurrection is known as a short weak refer-
ence, while one that tracks resurrection is known as a long weak reference. It is
advisable to refrain from using long weak references unless necessary; the state of
resurrected objects can be very unpredictable.
A long weak reference and a short weak reference will behave identically if the object does not
offer a Finalize method.
Weak references are useful in situations where a certain data structure requires a
lot of memory, and performance begins to degrade or you run out of memory
because the garbage collector has no objects to collect. The most common data
structure that benefits from the use of weak references is a tree structure that has
a lot of references and depth.