How can I implement a reusable pool of objects in C #?

I process a lot of data from a streaming socket. Data is used and left to clean the GC. I want to allocate a reusable pool and reuse it to prevent multiple GCs.

Can anybody help me?

+4
source share
1 answer

imho is a valid question. Especially when working with socket servers, where buffers are often allocated. It was called flies .

But I would not decide to use it easily.

class BufferPool<T> { private readonly Func<T> _factoryMethod; private ConcurrentQueue<T> _queue = new ConcurrentQueue<T>(); public BufferPool(Func<T> factoryMethod) { _factoryMethod = factoryMethod; } public void Allocate(int count) { for (int i = 0; i < count; i++) _queue.Enqueue(_factoryMethod()); } public T Dequeue() { T buffer; return !_queue.TryDequeue(out buffer) ? _factoryMethod() : buffer; } public void Enqueue(T buffer) { _queue.Enqueue(buffer); } } 

Using:

 var myPool = new BufferPool<byte[]>(() => new byte[65535]); myPool.Allocate(1000); var buffer= myPool.Dequeue(); // .. do something here .. myPool.Enqueue(buffer); 
+6
source

All Articles