.NET Weak and Strong References

When it comes to garbage collection there are weak references and strong references. When a root points to an object in managed heap, a strong reference exists. A weak reference is actually its own type; WeakReference. A WeakReference allows the garbage collector to collect the object, but also to let it be accessed. It all comes down to timing.

If the WeakReference instance is the only type holding a reference to an object on the managed heap, the object gets collected. However, if there exists a strong reference to the object at the same time, then no collection can occur.

A C# example:

object o = new object(); // Strong reference
// WeakReference object referencing o
WeakReference w = new WeakReference(o);	
// Removes strong reference, now only weak reference exists
o = null; 
// Does GC happen here?...
o = w.Target;
if ( o == null )  {
// A garbage collection occurred between o = null; 
// and o = wr.Target;
} else {
  // A garbage collection did not occur, and we can use the object.

Weak Reference should be used for caching. Start by holding a strong reference to a cache object. Then after some time of not being used, you move the reference to a WeakReference, setting the strong reference to null. Eventually the object will be garbage collected or returned to a strong reference if the object gets used again.


Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount


Or enter a custom amount


Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: