问题描述
我在使用Protobuf.net,它抛出一个非常奇怪的除了一些相当简单的code。在上线167,它抛出一个InvalidOperationException异常MetaType.cs的类型不能一次串行已经产生变化。这是什么意思,如何解决呢?
我的code是这样的:
此方法启动了所有的连载:
而(的Parallel.For(0,100,(我)=&GT!;
{
部件w;
锁定(F){W = f.CreateWidget(); }
SerialiseWidget(瓦特);
})。IsCompleted)
{
Thread.sleep代码(10);
}
pretty的简单,它只是遍历所有的并行,串行化和100的部件。
本连载方法也pretty的简单:
专用字节[] SerialiseWidget(部件w)
{
使用(MemoryStream的M =新的MemoryStream())
{
Serializer.Serialize< PacketChunk>(M,W);
返回m.ToArray();
}
}
最后,Widget类看起来是这样的:
[ProtoContract]
私有类的Widget
{
[ProtoMember(1)]
公众诠释一个;
[ProtoMember(2)]
公共字节[] B:
[ProtoMember(3)]
公共事℃; //事情本身就是一个protocontract
[ProtoMember(4)]
公众诠释D组;
[ProtoMember(5)]
公众诠释ê;
}
:我怀疑这可能是与事实,我在并行循环结束了。如何线程是Protobuf.net的那种事?
那么,它发现了一些奇怪的事情发生:)
一个电话在某些时候theading(应用程序启动时是明显的点)之前,只需添加到串行器。prepareSerializer,它应该原谅你......
编辑:思考它,有一个相当简单的变化,我可以做,以帮助特定的场景;我会调整,当我得到一个机会。此外,这应该只会影响的未发布的V2code(从SORCE code) - 在pre-内置DLL不受此AFAIK
I have some fairly simple code using Protobuf.net, which is throwing a very odd exception.In MetaType.cs on line 167 it throws a InvalidOperationException "The type cannot be changed once a serializer has been generated". What does this mean and how do I fix it?
My code looks like this:
This method starts off all the serialising:
while (!Parallel.For(0, 100, (i) =>
{
Widget w;
lock (f) { w = f.CreateWidget(); }
SerialiseWidget(w);
}).IsCompleted)
{
Thread.Sleep(10);
}
Pretty simple, it just loops through everything in Parallel, and serialises 100 widgets.
The serialise method is also pretty simple:
private byte[] SerialiseWidget(Widget w)
{
using (MemoryStream m = new MemoryStream())
{
Serializer.Serialize<PacketChunk>(m, w);
return m.ToArray();
}
}
And finally, the widget class looks like this:
[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;
}
Edit:: I suspect this may be to do with the fact I'm looping over in parallel. How threadsafe is Protobuf.net for that kind of thing?
Well, it noticed something odd happening :)
Just add a call to Serializer.PrepareSerializer at some point before the theading (app startup being the obvious point) and it should forgive you...
Edit: thinking about it, there is a fairly simple change I can make to help that specific scenario; I'll tweak that when I get a chance. Also, this should only affect the unreleased "v2" code (from sorce code) - the pre-built dll is not affected by this AFAIK.
这篇关于Protobuf.net&QUOT;类型不能一个串行器已经产生与QUOT变更一次;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!