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! 

 

Comments

No Comments

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.