Showing posts with label events. Show all posts
Showing posts with label events. Show all posts

September 20, 2011

Delegating Events & Event Serialisation Problems

Delegating an event to an underlying class:
...
private Helper helper;

// Normally implementation of add/remove are hidden but it is still possible to define them explicitly
public event EventHandler SomethingChanged
{
 add
 {
  this.helper.SomethingChanged += value;
 }
 remove
 {
  this.helper.SomethingChanged -= value;
 }
}
From the Event Accessors article by Stephen Toub, we get the following advice:

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;

August 10, 2008

Standard Delegates And Events

Standard event handler, no delegate definition necessary.
public event EventHandler xxxChanged;
Standard delegate handler, no delegate definition necessary.
using System;
//public delegate void Action()
Action xxxDelegate = new Action(xxxMethod);

public delegate TResult Func()
//Use it with anonymous methods:
Func methodCall = delegate() { return xxx.MethodReturningABool(); };
//There are other Func overloads, eg:
//public delegate TResult Func()
Func convert = delegate(int s)
         { return i.ToString() }; 

OR
// definition: public delegate void MethodInvoker()
using  System.Windows.Forms;
...
MethodInvoker xxxDelegate = new MethodInvoker(xxxMethod);