// using System; // using System.Linq; // using System.Collections.Concurrent; public class Pool<T> { private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>(); private readonly Func<T> _createOne; private readonly int _targetSize; public Pool(Func<T> createOne, int initialSize = 1, int targetSize = 3) { _createOne = createOne; _targetSize = targetSize; Enumerable.Range(0, initialSize).ToList() .ForEach(x => ReleaseOne(CreateOne())); } public T GetOne() { if (_queue.TryDequeue(out var item)) { return item; } else { return CreateOne(); } } private T CreateOne() { return _createOne(); } public void ReleaseOne(T item) { if (_queue.Count < _targetSize) { _queue.Enqueue(item); } else if (item is IDisposable disposable) { disposable.Dispose(); } } }
252100cookie-checkC# Connectionpool