gpt4 book ai didi

c# - 垃圾收集 - 一个有效但另一个无效,怎么会这样?

转载 作者:太空狗 更新时间:2023-10-29 18:31:29 24 4
gpt4 key购买 nike

<分区>

所以我有一个简单的 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();
}
}

你们能给我解释一下这是如何工作的吗?

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