Coffee on Mars
Coffee on Mars

Reputation: 998

Block garbage collector while analyzing weak references

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?

Upvotes: 5

Views: 275

Answers (1)

João Angelo
João Angelo

Reputation: 57688

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

Upvotes: 7

Related Questions