我有一些使用 Protobuf.net 的相当简单的代码,它抛出了一个非常奇怪的异常。 在第 167 行的 MetaType.cs 中,它抛出 InvalidOperationException“一旦生成序列化程序,就无法更改类型”。这是什么意思,我该如何解决?
我的代码是这样的:
这个方法开始所有的序列化:
while (!Parallel.For(0, 100, (i) =>
{
Widget w;
lock (f) { w = f.CreateWidget(); }
SerialiseWidget(w);
}).IsCompleted)
{
Thread.Sleep(10);
}
非常简单,它只是循环遍历并行中的所有内容,并序列化 100 个小部件。
序列化方法也很简单:
private byte[] SerialiseWidget(Widget w)
{
using (MemoryStream m = new MemoryStream())
{
Serializer.Serialize<PacketChunk>(m, w);
return m.ToArray();
}
}
最后,小部件类如下所示:
[ProtoContract]
private class Widget
{
[ProtoMember(1)]
public int a;
[ProtoMember(2)]
public byte[] b;
[ProtoMember(3)]
public Thing c; //Thing is itself a protocontract
[ProtoMember(4)]
public int d;
[ProtoMember(5)]
public int e;
}
编辑::我怀疑这可能与我并行循环有关。 Protobuf.net 对于这类事情的线程安全性如何?
最佳答案
How threadsafe is Protobuf.net for that kind of thing?
好吧,它注意到发生了一些奇怪的事情:)
只需在加载前的某个时刻添加对 Serializer.PrepareSerializer 的调用(应用程序启动是显而易见的点),它应该会原谅你...
编辑:考虑一下,我可以做一个相当简单的改变来帮助那个特定的场景;当我有机会时,我会调整它。此外,这应该只会影响未发布“v2”代码(来自源代码)- 预构建的 dll 不受此 AFAIK 的影响。
关于c# - Protocol Buffer .net "The type cannot be changed once a serializer has been generated",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4006296/