C#对象池实现源码
以下是一个简单的 C# 对象池实现源码:
public class ObjectPool<T> where T : new()
{
private readonly ConcurrentBag<T> _objects = new ConcurrentBag<T>();
private readonly Func<T> _objectGenerator;
public ObjectPool() : this(() => new T()) { }
public ObjectPool(Func<T> objectGenerator)
{
_objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator));
}
public T GetObject()
{
if (_objects.TryTake(out T item)) return item;
return _objectGenerator();
}
public void PutObject(T item)
{
_objects.Add(item);
}
}
该实现使用了 .NET 并发集合 ConcurrentBag<T> 来存储对象池中的对象,确保了线程安全性。GetObject() 方法从对象池中获取一个对象,如果池为空则使用 _objectGenerator 创建一个新对象。PutObject() 方法将一个对象放回对象池中。
使用方法:
// 创建一个对象池
ObjectPool<MyClass> pool = new ObjectPool<MyClass>();
// 从对象池中获取一个对象
MyClass obj = pool.GetObject();
// 使用对象
obj.DoSomething();
// 将对象放回对象池中
pool.PutObject(obj);
原文地址: https://www.cveoy.top/t/topic/ASV 著作权归作者所有。请勿转载和采集!