Joydip Kanjilal
Contributor

My two cents on weak references in .Net

opinion
Mar 11, 20164 mins
Software Development

Weak references in .Net create references to large objects in your application that are used infrequently so that they can be reclaimed by the garbage collector if needed

The GC is adept at reclaiming the memory occupied by managed objects. However, you should take extra measures to facilitate garbage collection for improved performance of your applications.

A weak reference is one that references an object in the memory while at the same time enabling the garbage collector to collect the object or reclaim the memory occupied by the object when the GC runs. An object that is reachable isn’t garbage collected by the runtime.

You can use weak references for objects that consume a lot of memory. In using weak references for such objects, you enable those objects to be garbage collected while at the same time allowing those objects to be recreated later if need be. So, if you have a large object in your application that you would use less frequently, you can use weak reference to such objects provided recreating such objects isn’t that expensive.

Note that when you create a weak reference to an object, an IntPtr to a GCHandle is stored internally by the weak reference you have created. The runtime uses this GCHandle to manage a table that contains weak references to objects. If an object has already been garbage collected, the value of IntPtr will be IntPtr.Zero. When the weak reference to the object is finalized, the corresponding entry of the weak reference to the object in the weak reference table is removed. If the weak reference to the object is still alive and you invoke the Target property on the weak reference, the actual object pointed to by the GCHandle of the weak reference is returned.

Creating a weak reference to an object doesn’t increase the life time of the object. It enables the garbage collector to reclaim the memory occupied by the object when no strong references to that object exist. The difference between a weak and a strong reference to an object is that while the former still allows the garbage collector to reclaim the memory occupied by that object, a strong reference to an object doesn’t allow the garbage collector to reclaim the memory occupied by that object if the object is reachable.

Programming weak reference in C#

To create a weak reference you would need to take advantage of the System.WeakReference class. Once you have created a weak reference to an object, you can use the Target property of the weak reference that you have created to check if the original object is still alive. The following code snippet shows how you can create a weak reference to an object.

Rectangle rectangle = new Rectangle(15, 10);

var weakReference = new WeakReference(rectangle);

You can use the IsAlive property to check if the weak reference to the object is still alive. Here’s a code listing that illustrates this.

static void Main(string[] args)

        {

            Rectangle rectangle = new Rectangle(15, 10);

            var weakReference = new WeakReference(rectangle);

            rectangle = null;

            bool isAlive = weakReference.IsAlive;

            if(isAlive)

            Console.WriteLine("The object is still alive");

            Console.Read();

        }

If the strong reference to the object is no longer available, you can leverage the Target property of the weak reference to use the object as shown in the code snippet given below.

bool isAlive = weakReference.IsAlive;

if(isAlive)

{

Rectangle rectangle = weakReference.Target as Rectangle;

//You can now use the rectangle object as usual

}

Short and long lived weak references

Weak references can either be short lived or long lived. The primary difference between short and weak reference is that while in the former case the Target property of the weak reference becomes null if the GC reclaims the object, in the latter case the long weak reference is alive even after the GC runs, i.e., it survives a GC cycle. Note that you should use long weak references with care as the state of the object can’t be predicted after finalization.

In essence, you should use short weak references when you would like to use an object that is in a usable state. On the contrary, a long weak reference is a good choice when you would like to use the object irrespective of its state. To create a long weak reference, you need to pass “true” as the second parameter to the overloaded constructor of the WeakReference class while creating the weak reference. The following code snippet illustrates this.

Rectangle rectangle = new Rectangle(15, 10);

var weakReference = new WeakReference(rectangle, true);

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author