About Serialization and Events
Recently I was writing a plugin system for a personal project of mine. The plugins ran in a seperate AppDomain, and thus communication between the application and the plugins would have to happen using serializable objects.
I ran into problems with this scenario. Whenever an object of the User type was passed between AppDomains, the framework threw a TypeException saying that another type, UserList, was not serializable. Now, it was not lying - I wasn't planning for the class to be passed between AppDomains, but why was the framework complaining about this class?
Normally, this type of exception means an object your trying to serialize is composed of one or more other classes that aren't serializable. I double-checked the fields and properties exposed by the User class. However, I saw no mention of a reference to the UserList class. I spent quite a while looking for a clue, and it took me quite a while before I realised a UserList object was subscribing to an event exposed on a User object. Turns out that when serializing an object for being passed between AppDomains, subscribers to its events are also being serialized and passed along. Marking the event with a NonSerialized attribute tells the framework not to do this, and hence fixed my problem.
It looks somewhat obvious once you know what's going on, but I guess I was thrown off by the fact that this behavior does not apply to XML serialization (eg. when passing objects to a web service).
Posted by Filip at 18:20. No comments yet.