Skip to content
Fast, light weight, thread safe object pool
C#
Branch: master
Clone or download
Latest commit 8ddf0bd Nov 19, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
samples more code coverage Nov 19, 2019
src update Nov 19, 2019
tests/LightObjectPool.Tests more code coverage Nov 19, 2019
.gitattributes Add .gitignore and .gitattributes. Nov 15, 2019
.gitignore Add .gitignore and .gitattributes. Nov 15, 2019
LightObjectPool.sln Adding code coverage Nov 19, 2019
README.md Update README.md Nov 19, 2019

README.md

LightObjectPool

What is LightObjectPool ?

A simple, light weight, thread safe object pool.

It also supports pooling of disposable types, managing the life time of pooled objects and performing early dispose when possible. Pool implementations implement a simple common interface, so they can be mocked or replaced with alternatives.

Supported Platforms

Currently;

  • .Net Framework 4.0+
  • .Net Standard 2.0+

How do I use it?

We got your samples right here

Install the Nuget package like this;

    PM> Install-Package LightObjectPool

NuGet Badge

Or reference the LightObjectPool.dll assembly that matches your app's platform.

Creating a Pool

Create a PoolPolicy instance to configure options and behaviour for the pool, T is the type of item being pooled. Create a new Pool instance passing the pool policy you created. Pool policies can be re-used across pools so long as the assigned Function and Action delegates are thread-safe.

    using LightObjectPool;
    //  Is for a StringBuilder pool.
    //  Synchronously resets the StringBuilder state when the item is returned to the pool.
    //  Pools at most 10 instances
    
    var pool = LightObjectPool.Pool.Create<StringBuilder>((s) => s.Clear(), 10);

Using a Pool

Use the Take method to retrieve an instance from the pool. Use the Add method to return an instance to the pool so it can be re-used.

    //Retrieve an instance from the pool
    var stringbuilder = pool.Get();
 
    //Do something with the stringbuilder   
    
    //Return the string builder to the pool
    pool.Return(stringbuilder);    

Using a Pool with Auto-Return Semantics

Instead of creating a pool for your specific type, create the pool for PooledObject where T is the type you actually want. Then you can use auto-return like this;

    //Retrieve an instance from the pool
    using (var pooledItem= pool.GetPooledObject())
    {
        //pooledItem.Value is the object you actually want.
        //If the pool is for tyhe type PooledObject<System.Text.StringBuilder> then
        //you can access the string builder instance like this;
        pooledItem.Value.Append("Some text to add to the builder");
        
    } // The item will automatically be returned to the pool here.
You can’t perform that action at this time.