views:

595

answers:

2

CancelEventArgs provides a Property called Cancel that different event handlers can set to tell the object that invoked the event whether it should continue execution cancel the action.

It seems that since events are multicast delegates, a simple raise of the event might invoke two delegates. The first one sets the Cancel property to true, the second one sets the Cancel property to false. Do component/framework 'cancelable' events support these scenarios and invoke each delegate one by one, checking the cancel flag at each step? What is the best practice to raise these types of events? Is only one instance of CancelEventArgs passed to each delegate? Are separate instances used?

+1  A: 

A little experiment quickly shows that they use 1 instance of Cancel (probably of the EventArgs object).

That makes it a bit of a gamble, with the outcome depending on the order in which the Eventhandlers were attached.

In the particular case of the CancelEventArgs I think the correct pattern would be to set Cancel to true or leave it alone, so the order shouldn't matter.

Henk Holterman
A: 

Tested:

public static void Main() {
 Event += (sender, e) => e.Cancel = true;
 Event += (sender, e) => e.Cancel = false;
 Event += (sender, e) => e.Cancel = true;

 var args = new CancelEventArgs();
 Event(null, args);

 WL(args.Cancel);
}

static event EventHandler<CancelEventArgs> Event;

The order of attached event handlers does matter.

Generally speaking, events with non-immutable event args and multicast delegates should not used together, but the .NET framework uses such events very extensively.

Michael Damatov