开发者

How can I implement a reusable object pool in C#?

开发者 https://www.devze.com 2023-03-05 03:18 出处:网络
I\'m processing a lot of data off a streaming socket. The data is used and left for the GC to clean up. I want to allocate a reuseable pool upfront and reuse it to prevent lots 开发者_如何学Pythonof G

I'm processing a lot of data off a streaming socket. The data is used and left for the GC to clean up. I want to allocate a reuseable pool upfront and reuse it to prevent lots 开发者_如何学Pythonof GCs.

Can anyone help me?


imho it's a valid question. Especially when working with socket servers where allocating buffers is done frequently. It's called flyweight pattern.

But I wouldn't take the decision to use it lightly.

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);
    }
}

Usage:

var myPool = new BufferPool<byte[]>(() => new byte[65535]);
myPool.Allocate(1000);

var buffer= myPool.Dequeue();
// .. do something here ..
myPool.Enqueue(buffer);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号