Kacho.ASyncObjectPool 1.1.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package Kacho.ASyncObjectPool --version 1.1.2
                    
NuGet\Install-Package Kacho.ASyncObjectPool -Version 1.1.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Kacho.ASyncObjectPool" Version="1.1.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Kacho.ASyncObjectPool" Version="1.1.2" />
                    
Directory.Packages.props
<PackageReference Include="Kacho.ASyncObjectPool" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Kacho.ASyncObjectPool --version 1.1.2
                    
#r "nuget: Kacho.ASyncObjectPool, 1.1.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Kacho.ASyncObjectPool@1.1.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Kacho.ASyncObjectPool&version=1.1.2
                    
Install as a Cake Addin
#tool nuget:?package=Kacho.ASyncObjectPool&version=1.1.2
                    
Install as a Cake Tool

AsyncObjectPool

A high-performance, async-friendly object pool for .NET, designed to efficiently manage reusable objects with dynamic scaling based on usage patterns.

Overview

AsyncObjectPool<T> provides a thread-safe, asynchronous object pool that supports dynamic growth and shrinking based on demand. It uses a Channel<T> for object storage and retrieval, with configurable policies for pool size, timeouts, and disposal. The pool is ideal for scenarios requiring expensive resource initialization, such as database connections, HTTP clients, or other heavy objects.

Features

  • Asynchronous Operations: Supports async object creation, renting, and returning.
  • Dynamic Scaling: Automatically grows or shrinks the pool based on demand, using configurable growth and shrink thresholds.
  • Timeout Policies: Customizable behavior for handling timeouts (e.g., wait, create new, or trigger monitoring).
  • Metrics: Provides real-time insights into pool usage, including active rentals, idle objects, and timeouts.
  • Exponential Moving Averages (EMA): Tracks rental times and idle ratios for adaptive pool management.
  • Disposable Support: Handles both IDisposable and IAsyncDisposable objects for proper resource cleanup.

Installation

Install via NuGet:

dotnet add package Kacho.AsyncObjectPool

Usage

Basic Example

using Kacho.AsyncObjectPool;
using System.Threading.Channels;

async Task Main()
{
    // Create a pool for strings with an async generator
    var pool = new AsyncObjectPool<string>(
        objectGenerator: async () =>
        {
            await Task.Delay(100); // Simulate expensive creation
            return "PooledObject";
        },
        options: new AsyncObjectPoolOptions
        {
            InitialPoolSize = 5,
            MinPoolSize = 2,
            MaxPoolSize = 10,
            TimeoutBehavior = TimeoutBehavior.CreateNewImmediately
        });

    // Initialize the pool
    await pool.InitializeAsync();

    // Use an object from the pool
    await pool.UseAsync(async obj =>
    {
        Console.WriteLine($"Using object: {obj}");
        await Task.Delay(50);
    });

    // Use with return value
    string result = await pool.UseAsync(async obj =>
    {
        await Task.Delay(50);
        return obj + "-Processed";
    });

    Console.WriteLine($"Result: {result}");

    // Check pool metrics
    var metrics = pool.Metrics;
    Console.WriteLine($"Current Pool Size: {metrics.CurrentSize}, Active Rentals: {metrics.ActiveRentals}");
}

Configuration Options

The AsyncObjectPoolOptions class allows customization of pool behavior:

  • InitialPoolSize: Number of objects to create on initialization (default: 10).
  • MinPoolSize: Minimum number of objects in the pool (default: 5).
  • MaxPoolSize: Maximum number of objects in the pool (default: 100).
  • GrowthFactor: Factor for pool growth when timeouts occur (default: 0.5).
  • MaxShrinkSize: Maximum number of objects to remove in one shrink cycle (default: int.MinValue).
  • MaxGrowthSize: Maximum number of objects to add in one growth cycle (default: int.MaxValue).
  • ShrinkIdleThreshold: Idle ratio threshold for shrinking the pool (default: 0.2).
  • EmaRentTimeAlpha: Smoothing factor for rental time EMA (default: 0.1).
  • EmaIdleRatioAlpha: Smoothing factor for idle ratio EMA (default: 0.5).
  • MonitoringLoopDelayMs: Delay between monitoring cycles in milliseconds (default: 2000).
  • TimeoutBehavior: Behavior when no objects are available within the timeout period (default: CreateNewImmediately).

Timeout Behaviors

The TimeoutBehavior enum defines how the pool handles cases when no objects are available within the specified timeout:

  • WaitForAvailable: Waits until an object becomes available.
  • CreateNewImmediately: Creates a new object immediately.
  • TriggerMonitoringWaitForAvailable: Signals the monitoring loop and waits for an object.
  • TriggerMonitoringCreateNewImmediately: Signals the monitoring loop and creates a new object.

Metrics

The Metrics property provides insights into pool performance:

  • CurrentSize: Total objects in the pool (active + idle).
  • ActiveRentals: Number of objects currently in use.
  • IdleCount: Number of objects available in the pool.
  • CurrentTimeouts: Number of timeouts since the last monitoring cycle.
  • ActiveRatio: Ratio of active rentals to total pool size.
  • IdleRatio: Ratio of idle objects to total pool size.
  • EmaRentTimeTicks: EMA of rental durations in ticks.

Notes

  • The pool uses Channel<T> for efficient, thread-safe object management.
  • Objects must implement IDisposable or IAsyncDisposable for proper cleanup.
  • The pool dynamically adjusts its size based on usage patterns, using EMA to smooth out fluctuations.
  • Ensure the objectGenerator function is thread-safe and handles exceptions appropriately.

License

MIT License

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Kacho.ASyncObjectPool:

Package Downloads
Kacho.RabbitMQ

Lightweight, async .NET wrapper for RabbitMQ.Client with robust connection management and dynamic entity declaration. Publishers leverage efficient channel pooling via Kacho.ASyncObjectPool, while consumers achieve high performance with parallel workers and bounded channels for fast, scalable message processing in .NET 8.0.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.1.0 131 1/19/2026
10.0.0 123 1/3/2026
1.1.2 248 6/2/2025
1.1.1 199 6/1/2025
1.1.0 149 6/1/2025
1.0.0 197 4/30/2025