Here is a structure I serialize in my project:
[Serializable]
class A : List<B> //root object being serialized
[Serializable]
class B
+ [A few serializable fields]
+ C customList
[Serializable]
class C : List<D>
[Serializable]
class D
+ [several serializable fields]
|
+ [NonSerialized] nonserializable3rdPartyClass data
+ string xmlOf3rdPartyData
|
+ [OnSerializing]
+ private void OnSerializing(StreamingContext context)
|
+ [OnSerialized]
+ private void OnSerialized(StreamingContext context)
|
+ [OnDeserialized]
+ private void OnDeserialized(StreamingContext context)
The nonserializable3rdPartyClass
, although not marked as [Serializable]
, provides .ToXml
and .FromXml
methods which I use in my .OnSerializing
and .OnDeserialized
methods, respectively, to store and retrieve the XML string in xmlof3rdPartyData
.
I've recently come across an issue where, under certain unknown circumstances (I have so far only been able to reproduce the issue using a serialized data file from a client, who first reported the issue), my .OnSerializing
and .OnSerialized
methods are only being called 57/160 times (where 160 is the total number of D
objects in the structure) when using a BinaryFormatter
to serialize to a file, leaving me with 103 D
objects with xmlOf3rdPartyData
set to null
. When cloning the structure using the method described here (which is basically the same as what I use to serialize to a file), I see the same results for .OnSerializing
/.OnSerialized
, but my .OnDeserialized
method is called the full 160 times.
This bit of code has been in use for months without issue (at least, as far as I know), and I'm still trying to determine why this is happening now and not earlier. I'm not seeing any first chance exceptions while debugging, and my breakpoints at the start of the methods are simply not being hit more than 57 times. Any ideas on why this would occur/how to fix it?
BinaryFormatter.Serialize
, myOnSerializing
/OnSerialized
marked methods are only being called ~35% of the time, but only in this one scenario that I can't yet qualify/find a reason for. – Civics