From 2bd23243f5c358cbf7d22b8c8cf816a6f5c5c278 Mon Sep 17 00:00:00 2001 From: Greg James Date: Mon, 4 Oct 2021 00:30:21 -0500 Subject: [PATCH] Added thread safe object pool --- algorithms/data-structures/ObjectPool.cs | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 algorithms/data-structures/ObjectPool.cs diff --git a/algorithms/data-structures/ObjectPool.cs b/algorithms/data-structures/ObjectPool.cs new file mode 100644 index 0000000..afa5745 --- /dev/null +++ b/algorithms/data-structures/ObjectPool.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Concurrent; + +namespace OctaneDownloadEngine +{ + public class ObjectPool + { + private ConcurrentBag _objects; + private readonly Func _objectGenerator; + + public ObjectPool(Func objectGenerator) + { + _objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator)); + _objects = new ConcurrentBag(); + } + + public T Get() => _objects.TryTake(out T item) ? item : _objectGenerator(); + + public void Return(T item) => _objects.Add(item); + + public void Empty() + { + _objects = null; + } + } +}