Weak References in .NET [C#]

Just to refresh our minds about strong references before starting to talk about weak references.A reference pointing to an object created by the new operator is called a Strong Reference and as long as this reference is still pointing to that object it will reside in memory. However, if a weak reference points to an object it gets collected by the garbage collector as soon as more memory is in need.

When to use Weak references?

For example, if you have data (not critical for your application) to be retrieved from an xml file, text file, or even a data source then you could use a weak reference. Even if it get collected by the garbage  collector you can still re-process the data.

 Below is a sample code to get a weak reference out of a strong one.

         // Create new strong reference to an object
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        // Load the xml into that object
        doc.Load(Server.MapPath("~/test.xml"));
        // Create weak reference out of doc object
        WeakReference docWeakRef = new WeakReference(doc);
        // Set the doc object to null;
        doc = null;

Now you can still get the strong reference to that object before using

docWeakRef.Target // which returns a strong reference to the weak object

Just remember before using the object always check the Target property if it is null then the object has been collected by the garbage collector and of course removed from the memory.

Happy Coding! 

 

Published 03 January 2008 09:56 PM by haissam

Comments

# Mazher said on 05 October, 2009 05:03 PM

Simple yet effective explaination. My Thanks.

# Yusuf Shabbir said on 05 November, 2009 12:33 AM

Hi

I am implementing weakreference in Singleton Pattern. Your explanation about weakrefrencing is quite clear, but i have a confusion. What i understand is in Singleton pattern we have to return the weakreference as a Instance Property and on the get method check if the weakreference.Target==null; if so then create a new Instance. Am i right?

This site

Search

Go

This Blog

Syndication

Sponsors

  • MaximumASP
  • Social Bookmarking
    Online Shopping
    asp.net hosting
    UK online local dating