Object Pool

Participants

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/95e853a1-aa0d-465d-9de0-4d1b3050781c/Untitled.png

var objPool = new ObjectPool<ExpensiveClass>();
var obj = objPool.Get();
objPool.Release(obj);

public class ExpensiveClass
{
    public int MyProperty { get; set; }
}

public class ObjectPool<T> where T : new()
{
    private readonly ConcurrentBag<T> _Items = new ConcurrentBag<T>();
    private int _Counter = 0;
    private readonly int Max = 10;

    public T Get()
    {
        if (_Items.TryTake(out T item))
        {
            _Counter--;
            return item;
        }
        else
        {
            var obj = new T();
            _Items.Add(obj);
            _Counter++;
            return obj;
        }
    }

    public void Release(T item)
    {
        if (_Counter < Max)
        {
            _Items.Add(item);
            _Counter++;
        }
    }
}

How to: Create an Object Pool by Using a ConcurrentBag

Rules of Thumb

Service Locator

public static class Locator
{
    private readonly static Dictionary<Type, Func<object>> _Services = new Dictionary<Type, Func<object>>();
    public static void Register<T>(Func<T> resolver) => _Services[typeof(T)] = () => resolver();
    public static T Resolve<T>() => (T)_Services[typeof(T)]();
    public static void Reset() => _Services.Clear();
}

Drawbacks