如何在C#中实现可重用的对象池?

ark*_*ina 4 c# object-pooling

我正在处理流式套接字上的大量数据.使用数据并留给GC进行清理.我想预先分配一个可重用的池并重复使用它来防止大量的GC.

谁能帮我?

jga*_*fin 6

imho这是一个有效的问题.特别是在使用经常完成分配缓冲区的套接字服务器时.它被称为飞重模式.

但我不会决定轻易使用它.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

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

var buffer= myPool.Dequeue();
// .. do something here ..
myPool.Enqueue(buffer);
Run Code Online (Sandbox Code Playgroud)