我创建了一个池类,当被询问时,它会查找或初始化一个项目并将其返回给调用者。我使用 aConcurrentQueue<T>
作为基础集合,但我不确定它是否适合使用。
我不需要按任何特定顺序排列项目,我只需要一个可以推送和弹出的线程安全集合。.NET 有为此目的的快速收集类吗?
编辑:我ConcurrentBag<T>
在花费者的回答后使用:
public sealed class Pool<T>
{
private readonly Func<T> initializer;
private readonly ConcurrentBag<T> bag;
public Pool(Func<T> initializer)
{
if (initializer == null)
throw new ArgumentNullException("initializer");
this.initializer = initializer;
this.bag = new ConcurrentBag<T>();
}
public Pool(Func<T> initializer, IEnumerable<T> collection)
{
if (initializer == null)
throw new ArgumentNullException("initializer");
if (collection == null)
throw new ArgumentNullException("initializer");
this.initializer = initializer;
this.bag = new ConcurrentBag<T>(collection);
}
public Pool(Func<T> initializer, int allocationCount)
: this(initializer)
{
if (allocationCount < 0)
throw new ArgumentOutOfRangeException("allocationCount");
for (int i = 0; i < allocationCount; i++)
this.bag.Add(initializer.Invoke());
}
public void Push(T item)
{
this.bag.Add(item);
}
public T Pop()
{
T item;
return this.bag.TryTake(out item)
? item
: this.initializer.Invoke();
}
}