Skip to content

Instantly share code, notes, and snippets.

@BashkaMen
Created June 17, 2021 22:31
Show Gist options
  • Save BashkaMen/21563f2c16e15f074328e84cf9b56baa to your computer and use it in GitHub Desktop.
Save BashkaMen/21563f2c16e15f074328e84cf9b56baa to your computer and use it in GitHub Desktop.
public class PoolItem<T> : IDisposable
{
private readonly Action<PoolItem<T>> _onRelease;
public T Value { get; }
public PoolItem(T value, Action<PoolItem<T>> onRelease)
{
_onRelease = onRelease;
Value = value;
}
public void Dispose()
{
_onRelease(this);
}
}
public class ObjectPool<T>
{
private readonly object _root = new();
private readonly Func<T> _fabric;
private readonly ConcurrentQueue<T> _pool = new();
public ObjectPool(Func<T> fabric)
{
_fabric = fabric;
}
public PoolItem<T> Take()
{
var item = _pool.TryDequeue(out var x) ? x : _fabric();
return new PoolItem<T>(item, Release);
}
public void Release(PoolItem<T> item)
{
_pool.Enqueue(item.Value);
}
}
public static class Test
{
public static async Task Run()
{
var httpPool = new ObjectPool<HttpClient>(() => new HttpClient());
using (var http = httpPool.Take())
{
await http.Value.GetAsync("asdasd");
}
Console.WriteLine("обьект вернулся в пул");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment