WeakReference Example
This page was last reviewed on Jun 28, 2021.
Dot Net Perls
WeakReference. This C# type influences the garbage collector. Most objects that are referenced must be kept in memory until they are unreachable.
But with WeakReference, objects that are referenced can be collected. We can use WeakReference to allow access to objects until they must be removed from memory.
An example. The WeakReference type is created using a constructor call. You must pass the object reference you want to point to the constructor. Here we use a StringBuilder object.
Next The garbage collector is run using GC.Collect. After this call, the object pointed to by the WeakReference no longer exists.
Tip If you don't call GC.Collect, the object will almost certainly still exist. This is not a guarantee.
Detail This is a boolean property that indicates whether the object pointed to by the WeakReference has been collected or not.
Detail The Target property returns an object that you stored in the WeakReference. It should be cast with as or is.
using System; using System.Text; class Program { /// <summary> /// Points to data that can be garbage collected any time. /// </summary> static WeakReference _weak; static void Main() { // Assign the WeakReference. _weak = new WeakReference(new StringBuilder("perls")); // See if weak reference is alive. if (_weak.IsAlive) { Console.WriteLine((_weak.Target as StringBuilder).ToString()); } // Invoke GC.Collect. // ... If this is commented out, the next condition will evaluate true. GC.Collect(); // Check alive. if (_weak.IsAlive) { Console.WriteLine("IsAlive"); } // Finish. Console.WriteLine("[Done]"); Console.Read(); } }
perls [Done]
A discussion. Is using the WeakReference type a good idea? Unfortunately, the behavior of the garbage collector is not always predictable and can even vary when the runtime is updated.
Also Using caches that are too large will cause reductions in performance because of memory locality degradation.
Thus WeakReference is often not ideal for performance work. A time-based expiration scheme would be more effective.
A review. WeakReference influences the GC. When a collection is done, either forced or invoked by the runtime, objects that are only referenced through WeakReference can be collected.
Therefore, you must check these objects for life upon each access. The IsAlive method is used for this purpose—it makes code more complex.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 28, 2021 (simplify).
© 2007-2024 Sam Allen.