Galin Iliev's blog

Software Architecture & Development

WeakReference ?!? Do we have strong one ?!

Have you used WeakReference class? I am sure you, probably, have in connection to GC and Memory Management in .NET (MSDN Magazine Article: Part1 and Part2). Especially if you have written complicated cache mechanisms. ASP.NET cache uses it internally.

It is very convenient because you can have the reference to some object and still allow this object to be collected by Garbage Collector (another description here) or in other words (according MSDN) "Represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection."
Here is one example from MSDN Magazine;

   1:  void Method() {
   2:     Object o = new Object();    // Creates a strong reference to the
   3:                                 // object.
   4:   
   5:     // Create a strong reference to a short WeakReference object.
   6:     // The WeakReference object tracks the Object.
   7:     WeakReference wr = new WeakReference(o);
   8:   
   9:     o = null;    // Remove the strong reference to the object
  10:   
  11:     o = wr.Target;
  12:     if (o == null) {
  13:        // A GC occurred and Object was reclaimed.
  14:     } else {
  15:        // a GC did not occur and we can successfully access the Object 
  16:        // using o
  17:     }
  18:  }
  19:   

Here is another example how can be used.

But how does it work? Here is good explanation.

To fully understand how weak references work, let's look inside the managed heap again. The managed heap contains two internal data structures whose sole purpose is to manage weak references: the short weak reference table and the long weak reference table. These two tables simply contain pointers to objects allocated within the managed heap.
Initially, both tables are empty. When you create a WeakReference object, an object is not allocated from the managed heap. Instead, an empty slot in one of the weak reference tables is located; short weak references use the short weak reference table and long weak references use the long weak reference table.
Once an empty slot is found, the value in the slot is set to the address of the object you wish to track—the object's pointer is passed to the WeakReference's constructor. The value returned from the new operator is the address of the slot in the WeakReference table. Obviously, the two weak reference tables are not considered part of an application's roots or the garbage collector would not be able to reclaim the objects pointed to by the tables.

Hope you find it helpful.

P.S. Here are some explanations how can resurrect objects in .NET.

Loading