为什么 GC 不收集我处理的对象?
Why aren't my disposed objects collected by GC?
我有一种有趣的场景,超出了我目前的知识范围。我希望以下测试能够成功,但是,除非我强制手动 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;
}
GC 不 运行 计时器,它 运行 内存压力。您在内存中没有足够的对象来自动触发 GC,这就是它没有发生的原因。
我有一种有趣的场景,超出了我目前的知识范围。我希望以下测试能够成功,但是,除非我强制手动 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;
}
GC 不 运行 计时器,它 运行 内存压力。您在内存中没有足够的对象来自动触发 GC,这就是它没有发生的原因。