Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 441703
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T20:59:56+00:00 2026-05-12T20:59:56+00:00

I don’t want to write my own because i’m afraid i might miss something

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T20:59:56+00:00Added an answer on May 12, 2026 at 8:59 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Don't want to pay for dedicated server for dev work. I don't want to
Don't be afraid to use any technical jargon or low-level explanations for things, please.
Don't know why people do not practice AJAX implementation for authentication systems. Is it
Don't know if I'm missing something here. I'd like to run multiple global variables
Don't know why this doesn't work. I can't do implicit animation for a newly
Don't know a whole lot about streams. Why does the first version work using
Don't know where else to ask, but from one day to the other my
Don't know if I worded the question right, but basically what I want to
Don't ask me why but i can't use this method because I need to
Don't know why I can't reply to people on here with only a small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.