Search code examples
c#.net.net-6.0.net-7.0object-pooling

Does .NET 6 have an ObjectPool class so I can pool my SFtpClient's?


I'm trying to find any code examples/docs about ObjectPooling in .NET 6.

I can see this exists in .NET 7 via these docs, but I'm unable to upgrade to .NET 7.

I did find -some- code somewhere (No I can't see where. It was on my work computer, not this one at home) that looked something like this:

using System.Buffers;

var sftpObjectPool = new ObjectPool<SftpClient>(() => new SftpClient(config), 50);

var sftpClient = sftpObjectPool.Get();

await sftpClient.UploadFileAsync(..);

sftpObjectPool.Return(sftpClient);

but I've not been able to find this class in the .NET BCL.

Is this possible?


Solution

  • ObjectPool<T> referenced in the docs is part of Microsoft.Extensions.ObjectPool package and is available for quite some time. It comes as dependency for ASP.NET Core (at least for 7th version), but for other projects types not based on Microsoft.NET.Sdk.Web you potentially will need to install it manually.

    Based on the usage some other class was used in your app though.

    With the ObjectPool<T> from the package something similar can look like:

    var objectPool = new DefaultObjectPool<SftpClient>(
        FactoryPolicy.Create(() => new SftpClient(config)), 
        maximumRetained: 50);
    
    class FactoryPolicy<T> : PooledObjectPolicy<T> where T : notnull
    {
        private readonly Func<T> _factory;
    
        public FactoryPolicy(Func<T> factory)
        {
            _factory = factory;
        }
    
        public override T Create() => _factory();
    
        public override bool Return(T obj) => true;
    }
    
    class FactoryPolicy
    {
        public static IPooledObjectPolicy<T> Create<T>(Func<T> factory) where T : notnull 
            => new FactoryPolicy<T>(factory);
    }