using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Serein.Library.Utils { public class TriggerResult { public TriggerDescription Type { get; set; } public TResult Value { get; set; } } /// /// 对象池队列 /// public class ConcurrentExpandingObjectPool where T : class, new() { private readonly ConcurrentQueue _pool; // 存储池中对象的队列 public ConcurrentExpandingObjectPool(int initialCapacity) { // 初始化对象池,初始容量为 initialCapacity _pool = new ConcurrentQueue(); // 填充初始对象 for (int i = 0; i < initialCapacity; i++) { _pool.Enqueue(new T()); } } /// /// 获取一个对象,如果池中没有对象,则动态创建新的对象 /// /// 池中的一个对象 public T Get() { // 尝试从池中获取一个对象 if (!_pool.TryDequeue(out var item)) { // 如果池为空,则创建一个新的对象 item = new T(); } return item; } /// /// 将一个对象归还到池中 /// /// 需要归还的对象 public void Return(T item) { // 将对象归还到池中 _pool.Enqueue(item); } /// /// 获取当前池中的对象数 /// public int CurrentSize => _pool.Count; /// /// 清空池中的所有对象 /// public void Clear() { while (_pool.TryDequeue(out _)) { } // 清空队列 } } /// /// 使用 ObjectPool 来复用 TriggerResult 对象 /// // 示例 TriggerResult 对象池 public class TriggerResultPool { private readonly ConcurrentExpandingObjectPool> _objectPool; public TriggerResultPool(int defaultCapacity = 30) { _objectPool = new ConcurrentExpandingObjectPool>(defaultCapacity); } public TriggerResult Get() => _objectPool.Get(); public void Return(TriggerResult result) => _objectPool.Return(result); } /// /// 触发类型 /// public enum TriggerDescription { /// /// 外部触发 /// External, /// /// 超时触发 /// Overtime, /// /// 触发了,但类型不一致 /// TypeInconsistency } }