...
...
using ProtoBuf;
[TestFixture]
public class UnmanagedHeap
{
[Test]
public void UnmanagedHeapAccess()
{
const int Iterations = 425 * 1000;
const string Key = "woo";
Bling obj = new Bling { Id = -666 };
Cache cache = new Cache();
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < Iterations; i++)
{
cache.Put(Key, obj);
obj = cache.Get<Bling>(Key);
}
cache.Remove(Key);
Console.WriteLine(sw.Elapsed.TotalMilliseconds);
}
[DataContract]
public class Bling
{
[DataMember(Order = 1)]
public int Id { get; set; }
}
public class Cache
{
private const int SizeFieldWidth = 4;
private readonly Dictionary<string, IntPtr> _lookup = new Dictionary<string, IntPtr>();
public void Put(string key, object obj)
{
IntPtr oldPtr = _lookup.TryGetValue(key, out oldPtr) ? oldPtr : IntPtr.Zero;
IntPtr newPtr = SerializeToHeap(obj, oldPtr);
_lookup[key] = newPtr;
}
public T Get<T>(string key)
{
IntPtr ptr = _lookup[key];
return DeserializeFromHeap<T>(ptr);
}
public void Remove(string key)
{
IntPtr ptr = _lookup[key];
Marshal.FreeHGlobal(ptr);
_lookup.Remove(key);
}
private static IntPtr SerializeToHeap(object obj, IntPtr oldPtr)
{
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, obj);
byte[] objBytes = ms.GetBuffer();
int newSize = (int)ms.Length;
bool requiresAlloc = true;
if (oldPtr != IntPtr.Zero)
{
int oldSize = GetObjectSize(oldPtr);
requiresAlloc = (oldSize != newSize);
}
IntPtr newPtr = requiresAlloc ? Marshal.AllocHGlobal(newSize + SizeFieldWidth) : oldPtr;
byte[] sizeField = BitConverter.GetBytes(newSize);
Marshal.Copy(sizeField, 0, newPtr, SizeFieldWidth);
Marshal.Copy(objBytes, 0, newPtr + SizeFieldWidth, newSize);
return newPtr;
}
}
private static T DeserializeFromHeap<T>(IntPtr ptr)
{
int size = GetObjectSize(ptr);
byte[] objBytes = new byte[size];
Marshal.Copy(ptr + SizeFieldWidth, objBytes, 0, size);
using (MemoryStream ms = new MemoryStream(objBytes))
{
return Serializer.Deserialize<T>(ms);
}
}
private static int GetObjectSize(IntPtr ptr)
{
byte[] sizeField = new byte[SizeFieldWidth];
Marshal.Copy(ptr, sizeField, 0, SizeFieldWidth);
int size = BitConverter.ToInt32(sizeField, 0);
return size;
}
}
}
put
并使用相同的键时,您都会有一个未经管理的内存泄漏。您需要在if (oldPtr!= IntPtr.Zero)
块内部添加if (requiresAlloc) Marshal.FreeHGlobal(oldPtr)
。此外,如果Cache
不为空并且您让其超出范围,则会出现令人讨厌的内存泄漏。但是,如果您将IntPtr
切换为调用Marshal.FreeHGlobal
的SafeHandle
,那么这个问题就可以解决了(使其可处置并使处置清空缓存也是一个不错的功能)。 - Scott Chamberlain是的,这里有100%托管代码。 上面的答案中建议使用ProtoBuf将无法提供100%的透明度,因为它不能正确映射多态引用和循环 + 需要特殊属性。NFX Pile除了[Serializable]之外不需要任何其他东西。
https://github.com/aumcode/nfx https://github.com/aumcode/nfx/blob/master/Source/NFX/ApplicationModel/Pile/IPile.cs
https://github.com/aumcode/nfx/blob/master/Source/NFX/ApplicationModel/Pile/ICache.cs
查看视频: https://www.youtube.com/watch?v=IUBF2Ncvbbs
https://www.youtube.com/watch?v=Dz_7hukyejQ
Apache 2.0