How to serialize in "destructor" ?

T

Trevor Balcom

I have a class which has a member variable of the type System.ArrayList.
I plan on having the ArrayList serialize/deserialize itself to/from XML. I
have worked out the code to do this and have the ArrayList is currently
deserializing in the constructor. When is the correct time to serialize the
ArrayList to XML? In C++ I would do this in the destructor. I see C# has a
destructor, but I am unsure about all of this IDisposable, Finalize, Dispose
and such. When would I perform cleanup code? Could someone explain these
terms to me ? Are there any source examples on MSDN to explain this ?
 
L

Lucean Morningside

Trevor Balcom said:
I have a class which has a member variable of the type System.ArrayList.
I plan on having the ArrayList serialize/deserialize itself to/from XML. I
have worked out the code to do this and have the ArrayList is currently
deserializing in the constructor. When is the correct time to serialize the
ArrayList to XML? In C++ I would do this in the destructor. I see C# has a
destructor, but I am unsure about all of this IDisposable, Finalize, Dispose
and such. When would I perform cleanup code? Could someone explain these
terms to me ? Are there any source examples on MSDN to explain this ?

You shouldn't even consider seralizing in the finalizer. As far as I know, when
the finalizer is executed, you can't guarantee that all objects that would have
been part of your object graph would still be available in memory. You might
consider seralizing explicitly before program termination. Or periodically if
that is not possible.

You might want to further explain the current porblem that you are trying to
solve here.

-LM
 
J

Jon Skeet

Lucean Morningside said:
You shouldn't even consider seralizing in the finalizer. As far as I know, when
the finalizer is executed, you can't guarantee that all objects that would have
been part of your object graph would still be available in memory.

I believe you can - they're still strongly reachable while your object
is strongly reachable. However, they may have been finalized before you
have, and generally not be in a very useful state. I agree it's not a
good idea to do anything like serialization in the finalizer though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top