Branislav Abadjimarinov's technical blog

WeakReference and .net memory management

Posted in C#, .NET, Memory Management by Branislav Abadjimarinov on 5/20/2010 1:50:00 AM - CST

WeakReference class is relatively unknown to the .net community. A weak reference in general is a reference to an object that doesn't stop the garbage collector from collecting an object. In its nature it is an agile reference to object - it can be useful to keep large objects in memory only if the application can afford it. If the application is pressed for memory it can collect the object which is weakly referenced.

The WeakReference class is drop dead simple to use. When you want to crate a weak reference to an object you just create a WeakReference and pass the object as a constructor parameter like this:

WeakReference weakRef = new WeakReference(referencedObjectInstance);

You can use the IsAlive Boolean property to check if an object is collected. And you can get the object instance using the Target property. It is good practice to use those two in combination to check first if the object is still available and than access it.

Another use of the WeakReference class is to check if objects are collected as expected. Let's say I have a simple Student class:

    public class Student
    {
        public string Name { get; set; }
    }

And I want to create an array of students. The array will not be garbage collected if an object from it is still alive. In the case where only one object form an array is alive it will prevent all the others array objects from being garbage collected. Creating the WeakReference will allow us to track if the objects are really collected.

    class Program
    {
        static void Main()
        {
            Student[] firstGrade = new Student[2];
            
            firstGrade[0] = new Student { Name = "Usefull Bob"};
            firstGrade[1] = new Student { Name = "Average Joe"};

            WeakReference weakRef = new WeakReference(firstGrade[1]);

            GC.Collect();

            Console.WriteLine(weakRef.IsAlive ? "Alive!" : "Dead");

            // Uncomment to prevent all objects in the array from garbadge collection
            // Console.WriteLine(firstGrade[0].Name);
        }
    }

There is also some differences if our application is running in Debug or Release mode. When the application is in Debug mode the garbage collector behavior is pretty much unpredictable as some objects are kept alive intentionally to support better debugging experience. If you want to get a real picture of the memory management in your app you have to do your profiling in Release mode. WeakReference class can also be used in Unit tests to verify if an object is garbage collected as expected.
 

Comments

None.

Comments are closed.
© Copyright 2017 Powered by AtomSite 1.3.0.0