我需要实现简单的线程安全内存管理来防止碎片。我已经阅读了一些关于this和this的文章,但我不知道如何在 C# 中开始实现。
要点:95% 的内存分配请求将是小于 1K 的块!
有人可以给我一些代码吗?
编辑
我已经写了一个Allocator
但是我没有在Alloc
方法中使用池。我如何更改它以使其使用池?
class Allocator
{
private int _id;
//TODO: it must be struct!
class Block
{
public int offset;
public int blockLength;
}
private readonly Dictionary<int, Block> idToBlock = new Dictionary<int, Block>();
private List<byte> rawData;
private int allocatedBlocksLength;
// sync
private readonly object _sync = new object();
public int Alloc(int count)
{
rawData.AddRange(new byte[count]);
idToBlock.Add(_id, new Block { offset = allocatedBlocksLength, blockLength = count });
var blockId = _id;
++_id;
allocatedBlocksLength += count;
return blockId;
}
public void Free(int id)
{
// Search in table
Block block;
if (!idToBlock.TryGetValue(id, out block))
return;
// remove object and update all offsets that after our block
foreach (var kv in idToBlock)
{
if (kv.Key == id)
continue;
if (kv.Value.offset > block.offset)
continue;
// changing indexes
kv.Value.offset -= block.blockLength;
}
// update how much left
allocatedBlocksLength -= block.blockLength;
}
}