Search code examples
c#asp.net-coreidisposableobjectpool

DefaultObjectPool do not dispose objects


c# documentation says:

When DefaultObjectPoolProvider is used and T implements IDisposable:

  • Items that are not returned to the pool will be disposed.

I've try some test app to check this out.

Looks like it's not disposing, why?

Example code:

using System;
using Microsoft.Extensions.ObjectPool;

namespace ConsoleApp9
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Started");
            using var a1 = new MyClass("a1");
            using var b1 = new MyClass("b1");

            var pool = new DefaultObjectPool<MyClass>(new DefaultPooledObjectPolicy<MyClass>());
            var a = pool.Get();
            var b = pool.Get();

            //pool.Return(a);
            //pool.Return(b);

            Console.WriteLine("Finished");
        }
    }

    public class MyClass : IDisposable
    {
        public MyClass()
        {
        }

        public MyClass(string id)
        {
            Id = id;
        }

        public void Dispose()
        {
            Console.WriteLine($"Disposing MyClass.Id={Id}");
        }

        public string Id { get; } = Guid.NewGuid().ToString();
    }
}

output:

Started
Finished
Disposing MyClass.Id=b1
Disposing MyClass.Id=a1

Solution

  • We should use DefaultObjectPoolProvider.Create<T>, then it will return DisposableObjectPool instead of DefaultObjectPool:

    Console.WriteLine("Started");
    using var a1 = new MyClass("a1");
    using var b1 = new MyClass("b1");
    
    var p = new DefaultObjectPoolProvider();
    var pool = p.Create<MyClass>();
    
    var a = pool.Get();
    var b = pool.Get();
    
    Console.WriteLine("Finished");
    

    output:

    Started
    Finished
    Disposing MyClass.Id=b1
    Disposing MyClass.Id=a1