Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 568
Coffee on Mars Avatar asked May 30 '11 09:05

Coffee on Mars


1 Answers

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

like image 117
João Angelo Avatar answered Sep 29 '22 12:09

João Angelo