#740 – Short vs. Long Weak References

You can create a WeakReference object that refers to a regular reference-typed object and lets you discover whether the original object has been garbage collected or not.  You can use the Target property of the WeakReference to reference the original object, if it’s still alive.

By default, a WeakReference object creates a short weak reference–the target of the weak reference becomes null and the IsAlive property reports false as soon as the object’s finalizer is called, but potentially before the object is actually garbage collected.

You can also create a long weak reference by passing a value of true as the second parameter to the WeakReference constructor.  The Target will remain non-null after the object has been finalized, up until the point in time when it actually gets garbage collected.  In this way, you retain access to an object that has been finalized, but not collected.

Advertisement