Reputation: 205
MSDN:
Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.
and
When you use a weak reference, the application can still obtain a strong reference to the object, which prevents it from being collected. However, there is always the risk that the garbage collector will get to the object first before a strong reference is reestablished.
My question is: Why can a WeakReference object be recreated easily? After the GC releases it, can be recreated easily, compared to normal objects?
Upvotes: 1
Views: 249
Reputation: 81159
The primary correct use of weak references is in situations where the deciding factor for whether a reference is likely to be useful is whether someone else holds a reference to the same thing. Two common examples of such situations:
In deciding whether to use a WeakReference
, one should decide whether one would be happy if the WeakReference
got invalidated the moment no other reference existed to its target. If one would want WeakReference
to remain valid for awhile, that's a sign that one should probably use some other caching mechanism.
Upvotes: 0
Reputation: 63338
You're misreading the text. When it says
Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.
it means
IF
you have an object that uses a lot of memory but could be easily recreated
THEN
a weak reference to this object could be useful
Upvotes: 5
Reputation: 57688
There is no difference, the MSDN documentation is trying to describe the use case for weak references, that is, weak references should be used associated with objects that use a lot of memory but at the same time are easily to be recreated.
A weak reference does not prevent an object from being garbage collected, so an object that is holding a lot of memory may be collected so that the memory can be reused. However if the object that was collected is expensive to recreate the benefits of using a weak reference and letting the object be garbage collected is lost when it comes time to use the object and a recreation is required because the object was collected.
Upvotes: 3