问题
Can someone give some examples of using weak references in .net projects ?
回答1:
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.
回答2:
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.
回答3:
There is a good example in the msdn page for WeakReference, a sample code which implements caching.
回答4:
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.
回答5:
An implementation of the mediator pattern
ViewModel locator using MEF
来源:https://stackoverflow.com/questions/5755860/weak-references-in-net