Delegating an event to an underlying class:
The trouble with events when it comes to .NET serialization is that they're backed by a private delegate field, and delegates are serializable. When you create a delegate for an instance method, the delegate maintains a reference to the instance on which to call that method, so when you serialize an object that contains an event, the formatter, while walking the object graph, will continue on down through the delegate attempting to serialize any instances registered with that delegate. A solution is to mark the backing store for the event with [NonSerializable]
Here is an example of the suggested solution:
... private Helper helper; // Normally implementation of add/remove are hidden but it is still possible to define them explicitly public event EventHandlerFrom the Event Accessors article by Stephen Toub, we get the following advice:SomethingChanged { add { this.helper.SomethingChanged += value; } remove { this.helper.SomethingChanged -= value; } }
The trouble with events when it comes to .NET serialization is that they're backed by a private delegate field, and delegates are serializable. When you create a delegate for an instance method, the delegate maintains a reference to the instance on which to call that method, so when you serialize an object that contains an event, the formatter, while walking the object graph, will continue on down through the delegate attempting to serialize any instances registered with that delegate. A solution is to mark the backing store for the event with [NonSerializable]
Here is an example of the suggested solution:
[NonSerializable] private EventHandler _myEvent;
No comments:
Post a Comment