//------------------------------------------------------------------------------ // 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有 // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 // CSDN博客:https://blog.csdn.net/qq_40374647 // 哔哩哔哩视频:https://space.bilibili.com/94253567 // Gitee源代码仓库:https://gitee.com/RRQM_Home // Github源代码仓库:https://github.com/RRQM // API首页:https://www.yuque.com/rrqm/touchsocket/index // 交流QQ群:234762506 // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; namespace TouchSocket.Core { /// /// 对象池 /// /// public class ObjectPool : IObjectPool where T : IPoolObject { private readonly ConcurrentQueue m_queue = new ConcurrentQueue(); private bool m_autoCreate = true; private int m_freeSize; /// /// 构造函数 /// /// public ObjectPool(int capacity) { Capacity = capacity; } /// /// 构造函数 /// public ObjectPool() { } /// /// 是否自动生成 /// public bool AutoCreate { get => m_autoCreate; set => m_autoCreate = value; } /// /// 对象池容量 /// public int Capacity { get; set; } /// /// 可使用(创建)数量 /// public int FreeSize => m_freeSize; /// /// 清除池中所有对象 /// public void Clear() { while (m_queue.TryDequeue(out _)) { } } /// /// 注销对象 /// /// public void DestroyObject(T t) { t.Destroy(); if (m_freeSize < Capacity) { Interlocked.Increment(ref m_freeSize); m_queue.Enqueue(t); } } /// /// 释放对象 /// public void Dispose() { Clear(); } /// /// 获取所有对象 /// /// public T[] GetAllObject() { List ts = new List(); while (m_queue.TryDequeue(out T t)) { ts.Add(t); } return ts.ToArray(); } /// /// 获取对象T /// /// public T GetObject() { if (m_queue.TryDequeue(out T t)) { t.Recreate(); t.NewCreate = false; Interlocked.Decrement(ref m_freeSize); return t; } if (m_autoCreate) { t = (T)Activator.CreateInstance(typeof(T)); t.Create(); t.NewCreate = true; } return t; } /// /// 预获取 /// /// public T PreviewGetObject() { m_queue.TryPeek(out T t); return t; } } }