手动监视对象的生存周期--------------C#

接下来,写一个拓展方法,监视对象在什么时候会被回收掉

 public static class GCWatcher
    {

        private static readonly ConditionalWeakTable<object, NotifyWhenGCd<string>> s_wt = new ConditionalWeakTable<object, NotifyWhenGCd<string>>();

        private sealed class NotifyWhenGCd<T>
        {
            private readonly T m_value;
            internal NotifyWhenGCd(T value)
            {
                m_value = value;
            }
            public override string ToString()
            {
                return m_value.ToString();
            }

            ~NotifyWhenGCd()
            {
                Console.WriteLine("DC'd"+m_value);
            }

        }


        public static T GCWatch<T>(this T @object,string tag) where T:class
        {
            s_wt.Add(@object, new NotifyWhenGCd<string>(tag));
            return @object;
        }
    }

 

 

在类中这样使用它,在对象回收时,会打印想要的提示语

 

    static void Main(string[] args)
        {
            object obj = new object().GCWatch("终于释放啦");
            obj = null;
            GC.Collect();
   
            Console.ReadKey();

        }

 

posted on 2017-08-23 09:52  你的乐哥哥  阅读(230)  评论(0编辑  收藏  举报