I've got an extension method that raises cancellable events, returning a bool if they're cancelled:
public static bool RaiseCancel<T>(this EventHandler<T> ev, object sender, T e) where T : CancelEventArgs
{
if (ev == null)
{
return false;
}
foreach (Delegate del in ev.GetInvocationList())
{
try
{
ISynchronizeInvoke invoke = del.Target as ISynchronizeInvoke;
if (invoke != null && invoke.InvokeRequired)
{
invoke.Invoke(del, new[] { sender, e });
}
else
{
del.DynamicInvoke(sender, e);
}
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
// if (e.Cancel) return true;
}
return e.Cancel;
}
However, I can't help thinking it should return immediately when a handler cancels it for the sake of efficiency, rather than continue to call the remaining handlers. As far as I'm aware, no handler of a cancellable event should EVER take any action other than to set the Cancel
property to true. That being the case, what's the point asking more handlers to make a decision that's already been made? On the other hand, it seems wrong NOT to call an event handler when it happens if an object is listening for the event.
Should I uncomment that if statement (and replace the return at the end of the method with return false;
) or not?
EDIT: I suppose if you're going to continue to call handlers, should I allow handlers themselves to make the decision (i.e., they can have if (e.Cancel) return;
at the beginning of the handler) if they want?