ObjectPool<T> or similar for .NET already in a library?

objectpool unity
objectpool java
objectpool c#
microsoft.extensions.objectpool example
objectpool<t>
microsoft.extensions.objectpool github
c# objectpool<t
microsoft.extensions.objectpool nuget

I don't want to write my own because i'm afraid i might miss something and/or rip off other people's work, so is there an ObjectPool (or similar) class existing in a library for .NET?

By object pool, i mean a class that assists caching of objects that take a long time to create, generally used to improve performance.

UPDATE:

I'd also put forward BufferBlock<T> from TPL DataFlow. IIRC it's part of .net now. The great thing about BufferBlock<T> is that you can wait asynchronously for items to become available using the Post<T> and ReceiveAsync<T> extension methods. Pretty handy in an async/await world.

ORIGINAL ANSWER

A while back I faced this problem and came up with a lightweight (rough'n'ready) threadsafe (I hope) pool that has proved very useful, reusable and robust:

    public class Pool<T> where T : class
    {
        private readonly Queue<AsyncResult<T>> asyncQueue = new Queue<AsyncResult<T>>();
        private readonly Func<T> createFunction;
        private readonly HashSet<T> pool;
        private readonly Action<T> resetFunction;

        public Pool(Func<T> createFunction, Action<T> resetFunction, int poolCapacity)
        {
            this.createFunction = createFunction;
            this.resetFunction = resetFunction;
            pool = new HashSet<T>();
            CreatePoolItems(poolCapacity);
        }

        public Pool(Func<T> createFunction, int poolCapacity) : this(createFunction, null, poolCapacity)
        {
        }

        public int Count
        {
            get
            {
                return pool.Count;
            }
        }

        private void CreatePoolItems(int numItems)
        {
            for (var i = 0; i < numItems; i++)
            {
                var item = createFunction();
                pool.Add(item);
            }
        }

        public void Push(T item)
        {
            if (item == null)
            {
                Console.WriteLine("Push-ing null item. ERROR");
                throw new ArgumentNullException();
            }
            if (resetFunction != null)
            {
                resetFunction(item);
            }
            lock (asyncQueue)
            {
                if (asyncQueue.Count > 0)
                {
                    var result = asyncQueue.Dequeue();
                    result.SetAsCompletedAsync(item);
                    return;
                }
            }
            lock (pool)
            {
                pool.Add(item);
            }
        }

        public T Pop()
        {
            T item;
            lock (pool)
            {
                if (pool.Count == 0)
                {
                    return null;
                }
                item = pool.First();
                pool.Remove(item);
            }
            return item;
        }

        public IAsyncResult BeginPop(AsyncCallback callback)
        {
            var result = new AsyncResult<T>();
            result.AsyncCallback = callback;
            lock (pool)
            {
                if (pool.Count == 0)
                {
                    lock (asyncQueue)
                    {
                        asyncQueue.Enqueue(result);
                        return result;
                    }
                }
                var poppedItem = pool.First();
                pool.Remove(poppedItem);
                result.SetAsCompleted(poppedItem);
                return result;
            }
        }

        public T EndPop(IAsyncResult asyncResult)
        {
            var result = (AsyncResult<T>) asyncResult;
            return result.EndInvoke();
        }
    }

In order to avoid any interface requirements of the pooled objects, both the creation and resetting of the objects is performed by user supplied delegates: i.e.

Pool<MemoryStream> msPool = new Pool<MemoryStream>(() => new MemoryStream(2048), pms => {
        pms.Position = 0;
        pms.SetLength(0);
    }, 500);

In the case that the pool is empty, the BeginPop/EndPop pair provide an APM (ish) means of retrieving the object asynchronously when one becomes available (using Jeff Richter's excellent AsyncResult<TResult> implementation).

I can't quite remember why it is constained to T : class... there's probably none.

ObjectPool<T> Class, Interface ObjectPool<T>. Type Parameters: T - Type of element pooled in this pool. All� The ObjectPool can be used in an app in multiple ways: Instantiating a pool. Registering a pool in Dependency injection (DI) as an instance. Registering the ObjectPoolProvider<> in DI and using it as a factory. How to use ObjectPool. Call Get to get an object and Return to return the object. There's no requirement that you return every object.

In the upcoming version of .NET (4.0), there's a ConcurrentBag<T> class which can easily be utilized in an ObjectPool<T> implementation; in fact the there's an article on MSDN that shows you how to do precisely this.

If you don't have access to the latest .NET framework, you can get the System.Collections.Concurrent namespace (which has ConcurrentBag<T>) in .NET 3.5 from Microsoft's Reactive Extensions (Rx) library (in System.Threading.dll).

ObjectPool (Apache Commons Pool 2.8.1 API), Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects� namespace DesignPattern.Objectpool {// The PooledObject class is the type that is expensive or slow to instantiate, // or that has limited availability, so is to be held in the object pool. public class PooledObject {DateTime _createdAt = DateTime.

CodeProject has a sample ObjectPool implementation. Have a look here. Alternatively, there are some implementations here, here, and here.

Object pool pattern, An object pool gives us the best of both worlds. To the memory manager, we're just allocating one big hunk of memory up front and not freeing it while the game � In the upcoming version of .NET (4.0), there's a ConcurrentBag<T> class which can easily be utilized in an ObjectPool<T> implementation; in fact the there's an article on MSDN that shows you how to do precisely this.

How about System.Collections.Generic.Dictionary?

Object Pool Design Pattern, Object pool pattern is a software creational design pattern which is used in situations where the cost of initializing a class instance is very high. Additionally, Unity uses Garbage Collection to deallocate memory that’s no longer in use. Repeated calls to Destroy() frequently trigger this task, and it has a knack for slowing down CPUs and introducing pauses to gameplay.

Sounds like you need a Factory pattern with caching.

You can try use .net reflector to look at the ThreadPool implementation.

Object Pool � Optimization Patterns � Game Programming Patterns, Example. Below is an example of the implementation of the Object pool design pattern namespace ObjectPool { class ObjectPool<T> where T :� ObjectPool. Instead of creating and destroying new objects all the time, this script reduces garbage by pooling instances, allowing you to seemingly create hundreds of new objects while only actually using a recycled few.

Object Pool Design Pattern, The Mem Ops ObjectPool class is capable of pooling instances of objects which can be reused. At first the ObjectPool is empty. When you� ObjectPool() { expirationTime = 30000; // 30 seconds locked = new Hashtable(); unlocked = new Hashtable(); } The checkOut() method first checks to see if there are any objects in the unlocked hashtable. If so, it cycles through them and looks for a valid one. Validation depends on two things.

Design patterns: Object pool. In this article, I will be talking…, Basically, an Object pool is a container which contains a specified amount of objects. When an object is taken from the pool, it is not available in the pool until it� Mostly, performance is the key issue during the software development and the object creation, which may be a costly step. Object Pool Pattern says that " to reuse the object that are expensive to create".

ObjectPool, public class Test : MonoBehaviour { private ResourcePool<GameObject> objectPool; [SerializeField] private GameObject enemyPrefab; void Start() { this.objectPool = new ResourcePool<GameObject>(Destroy,() => Instantiate(this.enemyPrefab) ); } void Update() { // To get existing object or create new from pool var newEnemy = this.objectPool.Rent

Comments
  • Perhaps you could describe what you expect this ObjectPool to do for you?
  • I believe en.wikipedia.org/wiki/Object_pool is a perfect description.
  • instead of a wiki link, please update your question with a description of what you want an ObjectPool to do.
  • Added, though the link still applies.
  • This is the best ever object pool on c# with explanation and example. Works even on windows phone stackoverflow.com/questions/2510975/…
  • Why exactly would you use a HashSet?
  • y'see, that code is now released under a CC-Wiki license so i can't use it without releasing my code under that license, and i'm not sure that i want to do that...
  • I don't understand how the proposed solution is related to the question. It seems like a fancy Queue rather than a ObjectsPool.
  • You could use it as inspiration for your ObjectPool, rather than directly copy it.
  • When I see code like this, I just kind of "drool" thinking about how much I don't understand it, and would like to understand it :) And, one day, perhaps, I will. Yes, I voted the message up. thanks,
  • While a dictionary might be used in an object pool implementation, it doesn't offer any of the features (such as a strategy for satisfying requests when the pool is empty), except storage.
  • It's usually, straight forward to add a "Factory" support as well as multithreading. The Pool might preload the objects on start (e.g from database) or create them on fly when requested. The full design of such class depends on your requirements.