MZy*_*tza 6 c# garbage-collection
我想测试不正确的对象引用并编写一个总是失败的测试.我将测试简化为以下行为:
    [Test]
    public void ScopesAreNotLeaking()
    {
        WeakReference weakRef;
        Stub scope = null;
        using (scope = new Stub())
        {
            weakRef = new WeakReference(scope);
        }
        scope = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Assert.That(weakRef.Target, Is.Null);
    }
然而,该测试在不使用的情况下执行相同的操作:
    [Test]
    public void ScopesAreNotLeaking()
    {
        WeakReference weakRef;
        Stub scope = new Stub();
        weakRef = new WeakReference(scope);
        scope = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Assert.That(weakRef.Target, Is.Null);
    }
使用的存根类很简单:
class Stub : IDisposable
{
    public void Dispose()  {}
}
有人可以解释一下这种行为,或者 - 甚至更好 - 有一个想法,如何确保对象被垃圾收集?
PS:如果之前有过类似的问题,请耐心等待.我只检查了标题中使用的那些问题.
我怀疑可能是本地的using语句引入的。使用 ildasm 查看函数中对该对象的所有引用是否在调用之前真正清除GC.Collect。还尝试将 using 位放在返回弱引用的单独函数中。
| 归档时间: | 
 | 
| 查看次数: | 475 次 | 
| 最近记录: |