Chr*_*.P. 8 c# garbage-collection
所以我有这个简单的Bell类,我正在测试垃圾收集:
public class Bell
{
public void Ring()
{
Console.WriteLine("Ding ding");
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在下面运行此代码段,则不会收集垃圾
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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我只检查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();
}
}
Run Code Online (Sandbox Code Playgroud)
你们能告诉我这是如何运作的吗?
您正尝试使用调试模式对其进行测试.GC在调试模式下不具有攻击性,因为它在释放模式下运行(优化开关打开).这使调试变得容易,否则你会在调试时发现奇怪的事情.例如:您可以尝试检查已经垃圾收集的变量的值.
在发布模式下运行代码,您可以看到Bell将是GC'd.
那是因为你的对象类型reference(源)
表示弱引用,它引用一个对象,同时仍然允许通过垃圾收集回收该对象。
以下可能可以解释为什么两种情况表现不同(来源)
弱引用允许垃圾收集器收集对象,同时仍然允许应用程序访问该对象。当不存在强引用时,弱引用仅在对象被收集之前的不确定时间内有效。当您使用弱引用时,应用程序仍然可以获得对该对象的强引用,这会阻止该对象被收集。但是,始终存在垃圾收集器在重新建立强引用之前首先到达对象的风险。
经过几次运行[带有一些测试用例]:我的意见
我认为这if-else是关键。之后,对象被重新引用,允许在清理对象Writeline之前获得强引用。GC
这句话又是关键
但是,始终存在垃圾收集器在重新建立强引用之前首先到达对象的风险。
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |