我正在使用最新的 protobuf-net lib 和 protobuf-net memcache 提供程序。我需要序列化自定义类型 MyClass 的列表
[ProtoContract]
public class MyClass{
[ProtoMember(1)]
public int a {get; set;}
[ProtoMember(2)]
public int b {get; set;}
}
所以我需要存储/检索:
List<MyClass> myList
当通过 protobuf 存储值然后从缓存中检索值时,一切都会顺利进行。但是,如果值存储在 memcache 中(以正确的 protobuf 格式),即来自另一个线程/应用程序,然后从缓存中检索该值,则由于类型字段的 NullReferenceExceptions,反序列化失败。
因此,当 set 首先执行时,序列化值的类型将存储在 typeCache 变量中,然后从该字典中检索。但是,如果值存在于 memcache 中但未在当前线程 typeCache 中设置,则 var 不包含该类型并在反序列化时抛出 NullReference。
有什么方法可以解决这个问题或解决方法吗?
更深入的调查:
enyim 的序列化/反序列化过程实现于ProtoTranscoder.cs
。它包含NetTranscoder
类有Dictionary<ArraySegment<byte>, Type> typeCache
。
因此,当 set 首先进入序列化类型时(即List<MyClass>
)存储在typeCache
var 一切顺利。如果值存在于内存缓存中,但在反序列化时未在当前应用程序/线程中设置,则通过以下代码检索:
type = Type.GetType(enc.GetString(buffer, keyOffset, len));
byte[] standaloneBuffer = new byte[len];
Buffer.BlockCopy(buffer, keyOffset, standaloneBuffer, 0, len);
key = new ArraySegment<byte>(standaloneBuffer, 0, len);
sync.EnterWriteLock();
try
{
// did somebody beat us to it?
Type tmp;
if (typeCache.TryGetValue(key, out tmp)) return tmp;
typeCache.Add(key, type);
return type; <-- Here it returns null, if type not present in typeCache
}
finally
{
sync.ExitWriteLock();
}
要重现该错误:
- 项目清单
- 在内存缓存中创建并存储一些列表(使用配置的原始转码器)
- 重新启动当前应用程序(或启动另一个线程)
- 尝试从“另一个线程”的内存缓存中按键获取值
这是此错误的堆栈跟踪:
[ArgumentNullException:值不能为空。
参数名称:类型]
ProtoBuf.Meta.TypeModel.PrepareDeserialize(Object value, Type& type) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:592
ProtoBuf.Meta.TypeModel.Deserialize(Stream source, Object value, Type type, SerializationContext context) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:577
ProtoBuf.Caching.Enyim.NetTranscoder.Enyim.Caching.Memcached.ITranscoder.Deserialize(CacheItem item) in c:\Users\akureniov\work\protobuf-net-1\protobuf-net.Enyim\protobuf-net.Enyim\ProtoTranscoder.cs:109
Enyim.Caching.MemcachedClient.PerformTryGet(String key, UInt64& cas, Object& value) +179
Enyim.Caching.MemcachedClient.TryGet(String key, Object& value) +42
Enyim.Caching.MemcachedClient.Get(String key) +15