對象池的創建 c#學習

 class Expensive
    {
        static Stack pool = new Stack();

        public static Expensive GetObjectFormPool()
        {
            return (Expensive)pool.Pop();
        }

        public static void ShutDownPool()
        {
            pool = null;
        }

        public Expensive()
        {
            pool.Push(this);
            Console.WriteLine("add a object");
        }

        ~Expensive()
        {
            if (pool != null)
            {
                Console.WriteLine("clear the memory");
                GC.ReRegisterForFinalize(this);
                pool.Push(this);
            }
        }

        public void PrintTest()
        {
            Console.WriteLine("Hello World!");
        }

        public static int GetCount()
        {
            if (pool != null)
            {
                return pool.Count;
            }
            return 0;
        }

    }


發佈了36 篇原創文章 · 獲贊 13 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章