Binary Serialization of Events

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a class with some public event fields. It appears that when I try to
serialize this class using a BinaryFormatter, the BinaryFormatter also tries
to serialize all the objects subscribed to the event. Is that right?

If that is what's going on, I don't want it to try to serialize subscribers
to the event. I tried marking the event with the [Nonserialized] attribute
but the compiler won't allow that. Any solutions?

Thanks
 
I had the same experience. I think the only solution is to implement
ISerializable and in GetObjectData() you only add the data you want
serialized.
 
if working in C# you should be able to mark the event as non-serialized

e.g.

[field: NonSerialized]
public event EventHandler MyEvent;


I working in VB.Net...unfortunately, up as far as VS2003, one could not
mark an event as NonSerialized.
I do not know if this has changed in VS2005.

You might try creating a base class in c# containing that event and
then inheiriting in from you VB.Net class.


hth,
Alan.
 
Dave said:
I have a class with some public event fields. It appears that when I
try to serialize this class using a BinaryFormatter, the
BinaryFormatter also tries to serialize all the objects subscribed to
the event. Is that right?

Yes, wonderful isn't it? <g> When you serialize an object all the fields
are serialise and this includes the delegate that the compiler adds for
the event. (The event itself is just metadata.) When the runtime
serializes a delegate it serializes the target of that delegate. All the
delegates that are used for events are MulticastDelegate which means
that they contain a linked list of delegates and hence this linked list
is serialized.

You can do funky things with this like serializing an object in a file
or a database and then raising the event days later when you deserialize
the object. The deserialized object does not have to be on the same
machine!
If that is what's going on, I don't want it to try to serialize
subscribers to the event. I tried marking the event with the
[Nonserialized] attribute but the compiler won't allow that. Any
solutions?

Yes, you can disambiguate the attribute. Remember that the compiler uses
the event keyword to generate code:

- metedata for the event
- a delegate field
- methods to add and remove delegates

So all you need to do is tell the compiler to apply the attribute to the
appropriate one:

[field: NonSerialized]
public event MyEventType MyEvent;

Richard
 
Back
Top