September 24, 2008

WeakReference (Class) in .NET

Strong Reference: The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object.

Weak Reference:

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.

When to use Weak Reference?

Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.

Suppose a tree view in a Windows Forms application displays a complex hierarchical choice of options to the user. If the underlying data is large, keeping the tree in memory is inefficient when the user is involved with something else in the application.

Weak Reference Example:

MyRefType mrt = new MyRefType();
//...

//Create weak reference
WeakReference wr = new WeakReference(mrt);
mrt = null; //object is no longer rooted
//...

//Has object been collected?
if(wr.IsAlive)
{
//Get a strong reference to the object
mrt = wr.Target;
//object is rooted and can be used again
}
else
{
//recreate the object
mrt = new MyRefType();
}