gpt4 book ai didi

c# - 垃圾收集器不会收集使用创建的对象

转载 作者:太空狗 更新时间:2023-10-29 21:19:29 26 4
gpt4 key购买 nike

我想测试不正确持有的对象引用并编写了一个总是失败的测试。我将测试简化为以下行为:

    [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);
}

使用的 stub 类很简单:

class Stub : IDisposable
{
public void Dispose() {}
}

有人可以向我解释这种行为,或者 - 甚至更好 - 知道如何确保对象被垃圾收集吗?

PS:如果之前有人问过类似的问题,请耐心等待。我只检查了标题中有using 的那些问题。

最佳答案

using 不是为了强制垃圾收集而设计的,而是为了确保调用 dispose。 Dispose 允许您释放非垃圾收集的资源,如文件句柄。当 C# 良好且准备就绪时,就会发生垃圾收集。

关于c# - 垃圾收集器不会收集使用创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6254865/

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