zoukankan      html  css  js  c++  java
  • 手动监视对象的生存周期--------------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();
    
            }
  • 相关阅读:
    Day11作业
    day12作业
    samba共享服务
    PHP7 redis扩展安装
    linux lin命令
    PhpStorm,Pycharm,Goland破解
    PHP规范PSR2
    PHP 过滤器(Filter)
    Linux下Redis的安装与配置
    linux命令汇总
  • 原文地址:https://www.cnblogs.com/xiaoleye/p/7416641.html
Copyright © 2011-2022 走看看