简体   繁体   English

从MemoryStream反序列化会在C#中引发OutOfMemory异常

[英]Deserialize from MemoryStream throws OutOfMemory exception in C#

This is a C# 3.0 Winform problem. 这是C#3.0 Winform问题。

I want to clone a big(not very big actually), complicated object. 我想克隆一个大(实际上不是很大)的复杂对象。 To do it lazily, I seralize it to a MemoryStream and use BinaryFormatter.UnsafeDeserialize(MemoryStream, null) method to get the cloned object. 为了做到这一点,我将它序列化为MemoryStream并使用BinaryFormatter.UnsafeDeserialize(MemoryStream,null)方法来获取克隆的对象。 Inside the UnsafeDeserialize() method, there is always an OutOfMemory exception thrown. 在UnsafeDeserialize()方法内部,始终会抛出OutOfMemory异常。 The memory should be sufficient. 内存应足够。

I read a bit about this as a .net bug but not sure whether it is the case here. 我读了一些有关.net的错误,但不确定这里是否是这种情况。

Anyone has any idea why this is happening? 任何人都知道为什么会这样吗? Any workround? 是否有工作流程? Thanks. 谢谢。

Perhaps a silly question but are you remembering to rewind the MemoryStream to the start of the stream before deserializing it? 也许这是一个愚蠢的问题,但是您还记得在反序列化流之前将MemoryStream倒回到流的开头吗?

It might also help to share some of your code. 共享一些代码也可能会有所帮助。

为什么使用UnsafeDeserialize而不是Deserialize

What is the object, and how big is it? 对象是什么,它有多大?

I've seen other people with a similar problems, and in some cases switching to a different serializer fixed it. 我见过其他人也遇到类似的问题,在某些情况下,切换到其他序列化器可以解决该问题。 I can suggest several that may be a good fit, depending on the scenario; 我可以根据情况建议一些合适的方法。 in particular - is the data a tree or a graph ? 特别是-数据是还是 (ie do child objects ever refer to siblings or their parents? Or just their own children). (即,孩子对象曾指兄弟姐妹或父母吗?还是仅指自己的孩子)。

我建议您改用FileStream,然后查看文件的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM