I'm experimenting with WeakReference, and I'm writing a code that checks if a weak reference is valid before returning a strong reference to the object.
if (weakRef.IsValid)
return (ReferencedType)weakRef.Target;
else
// Build a new object
How should I prevent the GC collecting the object between the "IsValid" and the "Target" calls?
You should instead do something like this:
var rt = weakRef.Target as ReferencedType;
if (rt != null)
// You now have a strong reference that you can safely use
If you succeed in obtaining a strong reference then you are assured that it will not be collected by the GC. A more complete example is provided in MSDN WeakReference page and if you haven't read it already you also may find useful the following:
Weak References
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