[英]Garbage collection - One works but not the other, how come? [duplicate]
所以我有这个简单的Bell类,我正在测试垃圾收集:
public class Bell
{
public void Ring()
{
Console.WriteLine("Ding ding");
}
}
如果我在下面运行此代码段,则不会收集垃圾
class Program
{
private static WeakReference reference;
private static void Main()
{
Console.WriteLine("Starting");
var bell = new Bell();
reference = new WeakReference(bell);
bell = null;
GC.Collect();
Console.WriteLine("Object still alive: {0}", reference.IsAlive);
if (reference.Target == null)
{
Console.WriteLine("Bell is no more!");
}
else
{
{
var theBell = (Bell)reference.Target;
theBell.Ring();
}
}
Console.ReadLine();
}
}
但是,如果我只检查reference.IsAlive如下,它是垃圾收集
class Program
{
private static WeakReference reference;
private static void Main()
{
Console.WriteLine("Starting");
var bell = new Bell();
reference = new WeakReference(bell);
bell = null;
GC.Collect();
Console.WriteLine("Object still alive: {0}", reference.IsAlive);
Console.ReadLine();
}
}
你们能告诉我这是如何运作的吗?
您正尝试使用调试模式对其进行测试。 GC在调试模式下不具有攻击性,因为它在释放模式下运行(优化开关打开)。 这使调试变得容易,否则你会在调试时发现奇怪的事情。 例如:您可以尝试检查已经垃圾收集的变量的值。
在发布模式下运行代码,您可以看到Bell
将是GC。
这是因为您的对象类型的reference
( 源 )
表示弱引用,它引用一个对象,同时仍然允许通过垃圾回收来回收该对象。
以下可能解释为什么两个场景的行为不同( 来源 )
弱引用允许垃圾收集器收集对象,同时仍允许应用程序访问对象。 弱引用仅在不存在强引用时收集对象之前的不确定时间内有效。 当您使用弱引用时,应用程序仍然可以获得对该对象的强引用,从而阻止其被收集。 但是,在重新建立强引用之前,始终存在垃圾收集器首先到达对象的风险。
经过多次运行[有一些测试用例]:我的意见
if-else
是我认为的关键。 在Writeline
之后,Object重新引用,允许在GC
清理对象之前获得强引用。
这句话再次成为关键
但是,在重新建立强引用之前,始终存在垃圾收集器首先到达对象的风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.