dcsimg

Deciding When to Use Weak References in .NET

WEBINAR:
On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


.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.



About the Author

Tapas Pal

I am working in Microsoft Technology for last 15 years and presently working with Cognizant Technology Solutions, India as Senior Architect. I have completed TOGAF 9.1,Microsoft Certification on .NET 1.1 , .NET 2.0, SQL Server 2005 and Sharepoint. Please visit my Blog - http://tapas-pal.blogspot.com/

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date