Skip to content

Instantly share code, notes, and snippets.

@TexRx
Forked from karlseguin/gist:1336377
Created May 23, 2012 01:57
Show Gist options
  • Save TexRx/2772822 to your computer and use it in GitHub Desktop.
Save TexRx/2772822 to your computer and use it in GitHub Desktop.
C# pool creator
public class Pool<T>
{
private readonly int _count;
private readonly Queue<T> _pool;
private readonly Func<Pool<T>, T> _create;
private readonly object _lock = new object();
public Pool(int count, Func<Pool<T>, T> create)
{
_count = count;
_create = create;
_pool = new Queue<T>(count);
for (var i = 0; i < count; ++i)
{
_pool.Enqueue(create(this));
}
}
public T CheckOut()
{
lock (_lock)
{
if (_pool.Count > 0)
{
return _pool.Dequeue();
}
}
return _create(this);
}
public void CheckIn(T value)
{
lock (_lock)
{
if (_pool.Count < _count)
{
_pool.Enqueue(value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment