As this article says: http://www.philosophicalgeek.com/2014/08/14/prefer-weakreferencet-to-weakreference/
If you are using WeakReference at all, it likely means you are somewhat memory conscious . In this case, allocating new WeakReference objects will contribute extra, unnecessary memory pressure.
So in this case, wouldn't it make more sense to make it a struct? And immutable while we're at it, and get rid of SetTarget().
A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError . A Weak reference is a reference that does not protect a referenced object from collection by GC.
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.
Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.
Notes. The reason you need a weak reference is so that the Garbage Collector can dispose of the objects when they are no longer needed. If two objects retain a strong reference to each other, then they can't be garbage collected. This is a memory leak.
The WeakReference
and WeakReference<T>
classes both have finalizers, which wouldn't be possible if they were structs.
If really necessary, you might be able to create your own custom weak-reference struct by making use of the weak variety of GCHandle
. (I believe, though I'm not certain, that WeakReference
and WeakReference<T>
use GCHandle
internally, although their finalizers ensure that everything is cleaned-up properly. Your custom struct would need to take care of its own clean-up without resorting to finalizers.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With