Vì vậy, tôi có điều này chỉ đơn giản là Chuông lớp mà tôi đang thử nghiệm thu gom rác thải trên:Bộ sưu tập rác - Một công trình nhưng không phải là công trình khác, làm thế nào đến?
public class Bell
{
public void Ring()
{
Console.WriteLine("Ding ding");
}
}
Nếu tôi chạy đoạn mã này dưới đây, nó không được thu gom rác thải
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();
}
}
Nếu tôi tuy nhiên chỉ kiểm tra reference.IsAlive như dưới đây, rác của nó được thu thập
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();
}
}
Các bạn có thể giải thích cho tôi cách hoạt động này không?
Nó hoạt động tương tự với tôi trong LINQPad, nhưng khi tôi thử nó trong VS 2013, nó luôn được thu thập - gỡ lỗi/phát hành, .NET 3.5, 4.0, 4.5, 4.5.1 – Ondra