#734 – Accessing the Original Object Referenced through a WeakReference

You can create a WeakReference instance that refers to an object and then use the WeakReference to determine whether the object has been garbage collected.

You can also refer back to the original object referenced by the WeakReference using its Target property.

            Dog dog = new Dog("Bowser");

            WeakReference dogRef = new WeakReference(dog);

            Dog origDog = (Dog)dogRef.Target;

When you refer to the original object in this way, you add a reference to it, which means that it won’t get garbage collected.

            Dog dog = new Dog("Bowser");

            WeakReference dogRef = new WeakReference(dog);

            Dog origDog = (Dog)dogRef.Target;

            dog = null;
            GC.Collect();

            // Bowser still alive at this point, since we still have
            // a reference to him.

            Console.WriteLine(string.Format("Object still alive: {0}", dogRef.IsAlive));

734-001

Advertisement

#732 – Destruction vs. Collection

Automatic memory management in C# means that the memory for a heap-based object is automatically released when there is no longer any user-written code that references the object.  This is done by the garbage collector.

An object goes through two distinct phases when it is no longer referenced–destruction and collection.

When an object is no longer referenced by any user-written code, other than code in a destructor, the object becomes eligible for destruction.

Once the object is eligible for destruction, it may be destructed at some point in the future, i.e. its destructor is called.

After the object is destructed and it is no longer being referenced by any code, including code in a destructor, the object becomes eligible for collection.

Once the object is eligible for collection, the garbage collector may at some point in the future release memory for the object.

#424 – The Garbage Collector

In C#, you don’t explicitly delete heap-based objects.  Instead, the CLR will reclaim memory from objects that are no longer used, by running a Garbage Collector.

The garbage collector (GC) can release memory only for managed objects created on the heap.  It’s only job is to release memory.  It can’t clean up or release other resources, like file handles or database connections.

The GC will typically perform garbage collection when the amount of available physical memory is becoming too low or when the amount of virtual memory consumed by your application is becoming too large.

You can’t predict when garbage collection is going to happen, or even if it’s going to happen, prior to an application terminating.