📄 defaultbufferpool.cs
字号:
namespace NCindy.Buffer
{
using NCindy;
using NCindy.Util;
using NCindy.Util.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
public sealed class DefaultBufferPool : IBufferPool
{
private long allocCount;
private static readonly int[] BufferSizes = new int[] { 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000 };
private long hitCount;
private static readonly DefaultBufferPool instance = new DefaultBufferPool();
private readonly Dictionary<int, Queue> internalPool = new Dictionary<int, Queue>();
private const int K = 0x400;
private static readonly ILogger logger = LogFactory.CreateLogger(MethodBase.GetCurrentMethod().ReflectedType);
private static readonly int MaxBufferPoolSize = BufferSizes[BufferSizes.Length - 1];
private DefaultBufferPool()
{
foreach (int num in BufferSizes)
{
this.internalPool.Add(num, Queue.Synchronized(new Queue()));
}
}
private static int AdjustCapacity(int capacity)
{
for (int i = 0; i < BufferSizes.Length; i++)
{
if (capacity <= BufferSizes[i])
{
return BufferSizes[i];
}
}
return capacity;
}
public IBuffer Allocate(int capacity)
{
IBuffer buffer;
if (capacity <= 0)
{
throw new ArgumentException("The capacity must LARGER than 0.", "capacity");
}
if (capacity > MaxBufferPoolSize)
{
return new PooledByteArrayBuffer(capacity);
}
Interlocked.Increment(ref this.allocCount);
int num = AdjustCapacity(capacity);
Queue queue = this.internalPool.get_Item(num);
if (queue.Count != 0)
{
while (queue.Count > 0)
{
try
{
WeakReference reference = (WeakReference) queue.Dequeue();
byte[] content = (byte[]) reference.Target;
if (content != null)
{
Interlocked.Increment(ref this.hitCount);
buffer = new PooledByteArrayBuffer(content, 0, num);
buffer.Limit = capacity;
return buffer;
}
}
catch (InvalidOperationException)
{
break;
}
catch (Exception exception)
{
if (logger.IsErrorEnabled)
{
logger.Error("", exception);
}
throw;
}
}
}
else
{
buffer = new PooledByteArrayBuffer(num);
buffer.Limit = capacity;
return buffer;
}
buffer = new PooledByteArrayBuffer(num);
buffer.Limit = capacity;
return buffer;
}
public static DefaultBufferPool Instance
{
get
{
return instance;
}
}
private sealed class PooledByteArrayBuffer : ByteArrayBuffer
{
public PooledByteArrayBuffer(int capacity) : base(capacity)
{
}
public PooledByteArrayBuffer(byte[] content, int offset, int capacity) : base(content, offset, capacity)
{
}
protected override void InternalRelease()
{
if (DefaultBufferPool.instance.internalPool.ContainsKey(this.Capacity))
{
Queue queue = DefaultBufferPool.instance.internalPool.get_Item(this.Capacity);
if (queue.Count < Configuration.MaxBufferPoolSize)
{
queue.Enqueue(new WeakReference(base.content));
}
}
base.InternalRelease();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -