c# - Object Pooling(對象池)

Object pooling的主要目的是提升程序性能。代碼會先從Pool中取得已經建好的對象實例,如果Pool中沒有對象實例才需要重新創建,以下代碼是一個示例:

namespace ObjectPool
{
    using System;
    using System.Collections;

    class Program
    {
        static void Main(string[] args)
        {
            Facotry facotry = new Facotry();

            for (int i = 0; i < 10; i++)
            {
                var stu = facotry.GetStudent();
                Console.WriteLine(stu.Name);
            }   
        }
    }

    public class Facotry
    {
        private static int _PoolMaxSize = 3;

        private static readonly Queue objPool = new Queue(_PoolMaxSize);

        public Student GetStudent()
        {
            Student student;
            if (Student.ObjectCounter >= _PoolMaxSize &&
                objPool.Count > 0)
            {
                student = RetrieveFromPool();
            }
            else
            {
                student = GetNewStudent();
            }
            return student;
        }

        private Student GetNewStudent()
        {
            Student stu = new Student();
            objPool.Enqueue(stu);
            return stu;
        }

        protected Student RetrieveFromPool()
        {
            Student stu;
            if (objPool.Count > 0)
            {
                stu = (Student)objPool.Dequeue();
                Student.ObjectCounter--;
            }
            else
            {
                stu = new Student();
            }
            return stu;
        }
    }

    public class Student
    {
        public static int ObjectCounter = 0;
        public Student()
        {
            ++ObjectCounter;
        }

        public string Name
        {
            get { return ObjectCounter.ToString(); }
        }
    }
}

另外,使用ConcurrentBag<T>實現Object Pool的示例如下:https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/how-to-create-an-object-pool

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章