如何强制完整垃圾收集在.NET 4.x的?垃圾、完整、NET

2023-09-03 03:25:14 作者:空叹花语意

我有一个问题,在.NET 4.x版在WeakReferences, 我跑测试,以确保某些对象不再被引用(使用在WeakReferences),我注意到的行为是不一致的整个框架的版本:

I've a problem with WeakReferences in .NET 4.x, I was running tests to make sure some objects were not referenced anymore (using WeakReferences) and I noticed the behavior is not consistent across framework versions:

using System;
using System.Text;
using NUnit.Framework;

[TestFixture]
public class WeakReferenceTests
{
    [Test]
    public void TestWeakReferenceIsDisposed()
    {
        WeakReference weakRef = new WeakReference(new StringBuilder("Hello"));

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.WaitForFullGCComplete();
        GC.Collect();

        var retrievedSb = weakRef.Target as StringBuilder;
        Assert.That(retrievedSb, Is.Null);
    }
}

结果:

.NET 2.0  PASS
.NET 3.0  FAIL
.NET 3.5  PASS
.NET 4.0  FAIL
.NET 4.5  FAIL

这是记载地方?

Is this documented somewhere?

有没有办法强制GC来收集参考在.NET 4.5?

Is there a way to force the GC to collect that reference in .NET 4.5?

在此先感谢。

推荐答案

下面是有关NCrunch问题。在code正常工作,我的机器的所有版本的框架,如果我取代测试用一个简单的调用 Debug.Assert的

The problem here is related to NCrunch. The code works fine on my machine for all versions of the framework if I replace the test with a simple call to Debug.Assert:

using System;
using System.Text;
using System.Diagnostics;

public class WeakReferenceTests
{
    public void TestWeakReferenceIsDisposed()
    {
        WeakReference weakRef = new WeakReference(new StringBuilder("Hello"));

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.WaitForFullGCComplete();
        GC.Collect();

        var retrievedSb = weakRef.Target as StringBuilder;
        Debug.Assert(retrievedSb == null);
    }
}