Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading