How would you like to be able to write the programming equivalent of “I might need this later….but I’m not so sure”? I’ll show you how.
A WeakReference is an object with a very interesting behavior, it allows you to keep a reference to an object while still making it possible for it to be garbage collected. See a previous post for a little more detail and links. Internally the WeakReference type uses an IntPtr to track a GCHandle that was acquired using the GCHandleType of Weak or WeakTrackResurrection.
This can be very useful if you are trying to managing the lifetime of objects in a cache or adding optimizations to possibly save time by not having to recreate an expensive object.
Let’s look at an example.
In your class you created two member variables:
WeakReference _weakRef = null;
Person _strongRef = null;
You created two new Person objects (which are simple objects I just created for this example, consisting of a Name property and some reference tracking code). Next you set the member variables to the newly created instances of the Person objects.
_strongRef = p;
_weakRef = new WeakReference(p1);
The difference here you’ll notice that _strongRef is just a regular normal reference, whereas _weakRef is set to a WeakReference object with the person object (p1) passed in as a parameter in the constructor.
If a garbage collection were to occur, or just for testing purposes you called it yourself with:
GC.Collect();
Then the p1 target object that is held by the _weakRef member variable should be garbage collected. You can write code to check:
if (_weakRef.IsAlive)
If the WeakReference is still alive you can convert the WeakReference to a strong or normal reference by using code like this:
Person p = _weakRef.Target as Person;
Now the p reference is treated as a strong reference and won’t be collected until it is no longer used. If you wanted to keep the reference around after the scope you could set that to a member variable.
There aren’t many times in programming that you get to say “maybe”. It’s usually binary — 1 or 0. A WeakReference seems to be one of them.
Chris Lasater | 29-Aug-06 at 12:01 am | Permalink
Nice article. Wasn’t as familiar with garbage collection via weakrefrences as I would have liked and this explained it better than msdn. Thanks!
Anonmyous | 15-Dec-06 at 9:27 am | Permalink
“This can be very useful if you are trying to managing the lifetime of objects in a cache or adding optimizations to possibly save time by not having to recreate an expensive object.”
Hmm i think a weak reference would not prevent you to recreate a G-collected object.
From the other post you describe.
“If the user were to open that screen up again, you could check the Target property of the WeakReference to see if the large object has been garbage collected yet. If the Target property is not null, you can create a new “strong reference” by setting a normal”.
If the target property is not null, there was an existing strong ref, and the weak-ref was useless because the object would not be garbage collected anyway. If the target property is null, your object has been collected and you have to recreate your object.
“You might keep a WeakReference around after you set the “strong reference” to the object to null when the user cancel’s out of the screen.”
If you set the strong reference to null, and you have a weakreference to it, the object is garbage collected.
So wheres the advantage in your example?
Anonmyous | 25-Jan-07 at 9:05 am | Permalink
Let me explain my point;
For me, a weak-reference is really usefull for Events.
Imagine you have a longliving objects, which has severeal interessting events for you.
Imagine a class/object that ist not that long living. So if you registerd a event from the “long-living” object, your short living object would not be garbagecollectet because it holds a “strong” ref. You have to unregister the event, for making your short-living object ready to be G-collected.
If there were only weak references, the G-Collector could say, fine your “short-living” class has only weakers so i G-Collect it.
That is my big advantage of Weakreferences. (I dont see the point from translating weakers to strongers, because i have to decide in my implemenation if my short-living object would “keep” alive or not.)
(Im just learning and try to unterstand your listened advantages).
RealWorld example;
Your “Car” Object listens to a global “GPS-Satellite” object and wants to now when he bypasses the border of the country. (the Country_Changed event
So if nobody uses this car, the car has not to listen to the satellite (becuase its useless).
If the car would “weakly” listen to this event, and there is nobody who is using this car (using this car would mean there is a strong ref to it), he could be G-Collected (whatever this means in this sample).
If he does “strongly” listen to the satelite, he makes it self “unCollectable”. –> Untill the GPS-Satellite would be destroyed itself which should not happen that often.
(You cant bash, destroy stomp the car) which will cause memory-leaks.
Hm
Greets
Anonmyous
Michael | 29-Jan-07 at 4:43 pm | Permalink
The other place you need a WeakReference is in circular data structures. For example, a circularly linked list will leak memory unless at least one of the References is weak. Or a simpler example is if A -> B and B -> A one must be weak.