views:

612

answers:

4

This is a C# 3.0 Winform problem.

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. Inside the UnsafeDeserialize() method, there is always an OutOfMemory exception thrown. The memory should be sufficient.

I read a bit about this as a .net bug but not sure whether it is the case here.

Anyone has any idea why this is happening? Any workround? Thanks.

+1  A: 

Perhaps a silly question but are you remembering to rewind the MemoryStream to the start of the stream before deserializing it?

It might also help to share some of your code.

Jon Grant
Yes, I set the position to 0 before deserialization.
Steve
A: 

Why are you using UnsafeDeserialize instead of Deserialize?

leppie
From MSDN: "In full trust scenarios, UnsafeDeserialize provides better performance than Deserialize."
Jon Grant
Didnt know that! :) Now to do that for my stuff! (although I find it is rather faster already).
leppie
A: 

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? (i.e. do child objects ever refer to siblings or their parents? Or just their own children).

Marc Gravell
The class is a tree structure.
Steve
Then perhaps consider protobuf-net; it is fast and efficient (space-wise) binary tree serializer. Note that it won't be compatible with existing BinaryFormatter serialized data. Caveat: I'm the author, but it is free; I'm not trying to sell you anything.
Marc Gravell
A: 

I suggest you try a FileStream instead, and see how big the file is.

John Saunders
I have tried that. The file is only 58MB. So it should have no memory problem at all. When the OutOfMemory exception is thrown, the application only uses under 500MB. I have 4G memory and I will assume single .net application uses up to 2G memory.
Steve