为什么GC不收集我的处置物?

时间:2016-02-03 16:41:11

标签: c# garbage-collection idisposable

我有一种超出我目前知识的有趣场景。我希望以下测试能够成功,但是,除非我强制使用手册GC.Collect,否则它会失败。

public class Foo : IDisposable {
    public void Dispose() {
        Debug.WriteLine("Disposed.");
    }
}

[Test]
public void CallScopeTest2()
{
    var list = new List<WeakReference>();
    for (var i = 0; i != 5; ++i)
    {
        list.Add(RunInner());
        // give time to GC
        Thread.Sleep(4000);
    }
    //GC.Collect(); // <--- if I uncomment this line, it will collect my objects and test passes

    // give yet a little more time to GC
    Thread.Sleep(5000);

    var c = list.Count(e => e.IsAlive);
    // here c == 5, unless I use the manual collect above
    c.ShouldEqual(0);
}

private static WeakReference RunInner()
{
    WeakReference result;
    using (var foo = new Foo())
    {
        result = new WeakReference(foo);
    }
    return result;
}

1 个答案:

答案 0 :(得分:1)

GC不在计时器上运行,它在内存压力下运行。内存中没有足够的对象来自动触发GC,这就是它没有发生的原因。