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开发者_Go百科 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
精彩评论