net coer 对象池

对象池的作用就是,因为重复创建对象,而带来的性能损伤,集中资源放入池中,如果拿对象,就去池中获取,用玩了,放回池去,防止gc 销毁。

对象池核心方法  一个怎么创建对象,一个状态管理(复位)。

在net core  对象池 是在扩展类Microsoft.Extensions.ObjectPool 中 定义类  public class DefaultObjectPool<T> : ObjectPool<T> where T : class

objectpool   是个抽象类 实现2个抽象方法

  //
    // 摘要:
    //     A pool of objects.
    //
    // 类型参数:
    //   T:
    //     The type of objects to pool.
    public abstract class ObjectPool<T> where T : class
    {
        //
        // 摘要:
        //     Gets an object from the pool if one is available, otherwise creates one.
        //
        // 返回结果:
        //     A T.
        public abstract T Get();

        //
        // 摘要:
        //     Return an object to the pool.
        //
        // 参数: 
        //   obj:
        //     The object to add to the pool.
        public abstract void Return(T obj);

        protected ObjectPool()
        {
            throw null;
        }
    }
  • Get函数用于从对象池获取对象,如果对象池没有可用对象,则会新建
  • Return函数用于对象使用完成后,将对象放回对象池,如果对象池容量已满,则交由系统GC回收。

定义一个管理池,放入user 对象 实现user 对象重复利用  我们定义池中2个对象  可以重复利用

using Microsoft.Extensions.ObjectPool;

namespace abptest.Core
{
    public interface IPool
    {

        public DefaultObjectPool<User> GetPool();
             
    }
    public class PoolManage : IPool
    {
        private DefaultObjectPool<User> defaultObject;
        public PoolManage()
        {
            defaultObject = new DefaultObjectPool<User>(new MyUserPolicy(), 2);
        }
        DefaultObjectPool<User> IPool.GetPool()
        {
            return defaultObject;   
        }
    }
}

定义一个抽象接口 IPooledObjectPolicy  里面包含2个接口

一个创建对象 一个 是用来复位

namespace Microsoft.Extensions.ObjectPool
{
    //
    // 摘要:
    //     Represents a policy for managing pooled objects.
    //
    // 类型参数:
    //   T:
    //     The type of object which is being pooled.
    public interface IPooledObjectPolicy<T> where T : notnull
    {
        //
        // 摘要:
        //     Create a T.
        //
        // 返回结果:
        //     The T which was created.
        T Create();

        //
        // 摘要:
        //     Runs some processing when an object was returned to the pool. Can be used to
        //     reset the state of an object and indicate if the object should be returned to
        //     the pool.
        //
        // 参数:
        //   obj:
        //     The object to return to the pool.
        //
        // 返回结果:
        //     true if the object should be returned to the pool. false if it's not possible/desirable
        //     for the pool to keep the object.
        bool Return(T obj);
    }
}

  自定义 一个myuserpolicey 

  public class MyUserPolicy : PooledObjectPolicy<User>
    {
        /// <summary>
        /// 如果池中的对象不够用  则调用下面的方法帮我创建
        /// </summary>
        /// <returns></returns>
        public override User Create()
        {

            return new User() { 
            
              Age =10,
               ID =3,
                Name="xiaoyong"
            };
       
         
        }
       // 把对象还到池子里的时候,做复位
        public override bool Return(User user)
        {
            try
            {
                // 这边是我们自定义的复位,成功不成功取决于我们
            
                //user.ID = 0;
                //user.Age = 0;
                 user = null;
                // 
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                // 没有复位成功也不会把当前对象放到对象池里面去
                return false;
            }
        }
    }

  注入 services

        public void ConfigureServices(IServiceCollection services)
        {

            services.TryAddSingleton<IPool, PoolManage>();
            services.AddControllersWithViews();
        }

web端 调用如下

        private readonly ILogger<HomeController> _logger;
        private readonly IPool Pool;

        public HomeController(ILogger<HomeController> logger, IPool pool)
        {
            _logger = logger;
            Pool = pool;
        }

        public IActionResult Index()
        {

            var user1 = new User()
            {
                Age = 1,
                 Name ="aaaaa"
            };


            var user2 = new User()
            {
                Age = 2,
                Name = "bbbb"
            };

            var user3 = new User()
            {
                Age = 3,
                Name =    "ccc"
            };


            Pool.GetPool().Return(user1);

            Pool.GetPool().Return(user2);


            Pool.GetPool().Return(user3);

            // 下面是通过池子拿对象
            Console.WriteLine(Pool.GetPool().Get().Age);
            Console.WriteLine(Pool.GetPool().Get().Age);
            //池子里面已经拿不到,
            Console.WriteLine(Pool.GetPool().Get().Age);
            
            return View();
        }

1 和2  拿到了    3 没有在池中 所以重新创建了 user  

原文地址:https://www.cnblogs.com/jasontarry/p/15669594.html