Serialization of GH_Goo<T> with references

Dear all,

I have a set of custom data-objects which contain references to identical objects. When serializing these data-objects I would like to maintain the references and serialize the referenced data only once.

My first idea was to use a cache with a Dictionary<T, Guid>. When writing the data, the Dictionary can be used to check whether a referenced object has already been serialized or not. If already on disk, the Guid is written instead of the object, otherwise a Guid gets created and the data gets saved.

Now my problem is how to decide when to clear the cache. It needs to be cleared between two full write-operations to different streams - otherwise the referenced objects do not get saved in the second write-operation.

I tried to compare the reference to the GH_IWriter-object that get passed to the GH_Goo<>.Write(GH_IWriter writer)-method with a GH_IWriter-reference I store in the cache, to clear the cache when they are not equal. This does not work however, the equality test always fails.

Is there a reliable way to check, whether a full read or write operation has completed?