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

编程入门 行业动态 更新时间:2024-10-27 04:35:45
本文介绍了如何强制完整垃圾收集在.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的?

本文发布于:2023-11-17 17:08:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1610406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:垃圾   完整   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!