-
-
Save TexRx/2772822 to your computer and use it in GitHub Desktop.
C# pool creator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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