本文介绍了如何强制完整垃圾收集在.NET 4.x的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题,在.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); } }更多推荐
如何强制完整垃圾收集在.NET 4.x的?
发布评论