gpt4 book ai didi

c# - 测试/验证弱引用

转载 作者:可可西里 更新时间:2023-11-01 03:09:38 24 4
gpt4 key购买 nike

我想验证设置 WeakReference 的代码不会意外持有对引用对象的强引用。 (这里的 an example 说明了如何很容易不小心这样做。)

这看起来是检查无意强引用的最佳方式吗?

TestObject testObj = new TestObject();
WeakReference wr = new WeakReference(testObj);

// Verify that the WeakReference actually points to the intended object instance.
Assert.Equals(wr.Target, testObject);

// Force disposal of testObj;
testObj = null;
GC.Collect();
// If no strong references are left to the wr.Target, wr.IsAlive will return false.
Assert.False(wr.IsAlive);

最佳答案

我就此与 Microsoft 取得了联系并了解到/确认:

  • GC.Collect() 强制进行阻塞垃圾回收。
  • GC.Collect() 运行时,它不会神秘地跳过符合收集条件的对象。遵循可预测的规则来确定收集哪些对象。只要您了解这些规则(即如何处理可终结对象),您就可以强制销毁特定对象,尽管被销毁对象使用的内存可能会或可能不会被释放。

有关我的博客的更多信息:Can .Net garbage collection be forced?

关于c# - 测试/验证弱引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5912797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com