在分析弱引用时阻止垃圾收集器

Cof*_*ars 5 .net c# garbage-collection weak-references

我正在尝试使用WeakReference,我正在编写一个代码,用于在返回对对象的强引用之前检查弱引用是否有效.

if (weakRef.IsValid)
    return (ReferencedType)weakRef.Target;
else
    // Build a new object
Run Code Online (Sandbox Code Playgroud)

我应该如何阻止GC在"IsValid"和"Target"调用之间收集对象?

Joã*_*elo 7

你应该做这样的事情:

var rt = weakRef.Target as ReferencedType;

if (rt != null)
    // You now have a strong reference that you can safely use
Run Code Online (Sandbox Code Playgroud)

如果您成功获得了强有力的参考,那么您可以放心,GC不会收集它.MSDN WeakReference页面中提供了一个更完整的示例,如果您还没有阅读它,您可能会发现以下内容:

弱参考