为什么未收集弱参考目标

时间:2018-10-11 12:52:23

标签: pointers .net-core weak-references

你好,我试图了解WeakReference,并且我已经做了一个小实验:

public class Slave {
            public string Name { get; set; }


        }
        public class WeakOwner{
            public List<WeakReference<Slave>> slaves = new List<WeakReference<Slave>>();
        }


        static void Main(string[] args) {
            Slave slave1 = new Slave { Name = "ditone" };
            Slave slave2 = new Slave { Name = "aditzone" };

            WeakOwner owner = new WeakOwner();

            owner.slaves.Add(new WeakReference<Slave>(slave1));
            owner.slaves.Add(new WeakReference<Slave>(slave2));
            slave1 = null;
            slave2 = null;
            GC.Collect(); 

            Console.ReadLine(); // line where i stopped the debugger 
        }

我不明白对象owner是否添加了两个WeakReference -s并且我将被引用的对象设置为null,然后又将它们GC设置为i,则没有其他引用可以保存那么为什么当我使用调试器访问owner.slaves的项目时,我仍然发现两个Target属性不为空?它们不应该为空吗?还有谁引用slave1slave2来保持生命?

0 个答案:

没有答案