Deciding When to Use Weak References in .NET

.NET WeakReference Example

The .NET WeakReference Class represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection. Now, let’s see an example. Create a console application from Visual Studio and name it MyWeakReference.

Create a WeakReference object and pass an object reference to the constructor call. In the following example, I have used the StringBuilder object.

static WeakReference myweakerenceobject;
myweakerenceobject = new WeakReference(new StringBuilder("My weak
   reference object."));

During execution, in the middle of the program, the garbage collector is executed by using GC.Collect. After this call, the object pointed to by the WeakReference no longer exists. After the call, I have checked if the object is still alive. Refer to the following code snippet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWeakReference
{
   class Program
   {
      static WeakReference myweakerenceobject;
      static void Main(string[] args)
      {
         myweakerenceobject = new WeakReference(new
            StringBuilder("My weak reference object."));
         if (myweakerenceobject.IsAlive)
         {
            Console.WriteLine((myweakerenceobject.Target as
               StringBuilder).ToString());
         }
         GC.Collect();
         // Check if still alive after GC call.
         if (myweakerenceobject.IsAlive)
         {
            Console.WriteLine("Object Alive");
         }
         Console.WriteLine("[I'm Done]");
         Console.Read();
      }
   }
}

The IsAlive property mentioned in the preceding code is an important property on the WeakReference type. This Boolean property indicates whether or not the object pointed to by the WeakReference has been collected.

I have also used the Target property in the code snippet. That returns an object that contains the reference to the instance I stored in the WeakReference. However, if the original object has already been garbage collected, the Target property will be null and then you can no longer reference the original object.

What Are the Differences Between Weak and Strong References?

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.

Should We Use WeakReference?

A developer should use long weak references only when necessary because the object is unpredictable after finalization. We should avoid using weak references to small objects because the pointer itself may be as large or larger. Instead of weak references, we should develop an effective caching policy in an application.

WeakReference is often used for implementing Weak Events. Event handlers are a frequent cause of memory leaks, particularly when you have a long-lived service with events that multiple instances subscribe to.

Conclusion

That’s all for today. The following references are for for further study.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read