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

发布了130 篇原创文章 · 获赞 20 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/yuxuac/article/details/103164606