Created
March 15, 2020 15:10
-
-
Save MiloszKrajewski/da99a60963ef34fcbe4caeb53fee0570 to your computer and use it in GitHub Desktop.
Simple object pool
This file contains 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 ConcurrentQueue<T> _queue; | |
private readonly Func<T> _create; | |
private readonly Action<T> _reset; | |
private readonly Action<T> _destroy; | |
private int _freeSlots; | |
public Pool(Func<T> create, Action<T> reset, Action<T> destroy, int size) | |
{ | |
_queue = new ConcurrentQueue<T>(); | |
_create = create; | |
_reset = reset ?? (_ => { }); | |
_destroy = destroy ?? (_ => { }); | |
_freeSlots = size; | |
} | |
public T Borrow() | |
{ | |
if (!_queue.TryDequeue(out var resource)) | |
return _create(); | |
_reset(resource); | |
Interlocked.Increment(ref _freeSlots); | |
return resource; | |
} | |
public void Return(T resource) | |
{ | |
if (Interlocked.Decrement(ref _freeSlots) < 0) | |
{ | |
Interlocked.Increment(ref _freeSlots); | |
_destroy(resource); | |
} | |
else | |
{ | |
_queue.Enqueue(resource); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment