Reputation: 1367
Can someone give some examples of using weak references in .net projects ?
Upvotes: 4
Views: 1645
Reputation: 1756
One scenario is where you want an object to have singleton behavior, but you don't want it to stick around forever with a long-lived reference. For example:
class ExpensiveSingleton
{
private static WeakReference _instanceWeakRef;
private ExpensiveSingleton() { ... your expensive ctor ... }
public static ExpensiveSingleton Instance
{
get
{
ExpensiveSingleton reference = null;
if(_instanceWeakRef != null)
reference = _instanceWeakRef.Target as ExpensiveSingleton; // Try a cheap access
if(reference == null)
{
reference = new ExpensiveSingleton(...); // Pay the cost
_instanceWeakRef = new WeakReference(newInstance);
}
return reference;
}
}
}
(For brevity, this wasn't made thread safe)
This ensures that all strong references you obtain to that object are the same object, and that when all strong refs are gone, the object will eventually be collected.
Upvotes: 3
Reputation: 9495
Think about cache with 2 levels. So objects in the 1st level are referenced with normal references and in then 2nd level with weak references. Thus if you want to expiry your object from the 1st level you can put it in the 2nd level.
Next time, when client tries to access this object if you have enough memory object will be promoted from the 2nd level, however if memory is not enough and object was collected you will have to recreate your object. Sometimes it will be recreated or retrieved from expensive store but in some situation you will be able to find it in the 2nd level.
Upvotes: 4
Reputation: 20157
Some good articles:
http://www.switchonthecode.com/tutorials/csharp-tutorial-weak-references
http://www.dotnetperls.com/weakreference
http://www.codeproject.com/KB/dotnet/WeakReference.aspx
One of the big wins when using them is for event subscriptions. Also for object caches.
Upvotes: 1
Reputation: 8885
There is a good example in the msdn page for WeakReference, a sample code which implements caching.
Upvotes: 1