Block garbage collection for weak link analysis

I am experimenting with WeakReference, and I am writing code that checks to see if a weak link is valid before returning a strong link to an object.

if (weakRef.IsValid)
    return (ReferencedType)weakRef.Target;
else
    // Build a new object

How to prevent GC object collection between calls to "IsValid" and "Target"?

+5
source share
1 answer

Instead, you should 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 manage to get a strong link, you will make sure that the GC will not be built. A more complete example is provided on the MSDN WeakReference page , and if you have not read it yet, you can also find the following:

Weak links

+7
source

All Articles