tags:

views:

746

answers:

1

In System.ComponentModel, there's a class called CancelEventArgs which contains a Cancel member that can be set in event listeners. The documentation on MSDN explains how to use that to cancel events from within a listener, but how do I use it to implement my own cancelable events? Is there a way to check the Cancel member after each listener fires, or do I have to wait until after the event has fired all its listeners?

+4  A: 

To check each listener in turn, you need to manually get the handlers via GetInvocationList:

class Foo
{
    public event CancelEventHandler Bar;

    protected void OnBar()
    {
        bool cancel = false;
        CancelEventHandler handler = Bar;
        if (handler != null)
        {
            CancelEventArgs args = new CancelEventArgs(cancel);
            foreach (CancelEventHandler tmp in handler.GetInvocationList())
            {
                tmp(this, args);
                if (args.Cancel)
                {
                    cancel = true;
                    break;
                }
            }
        }
        if(!cancel) { /* ... */ }
    }
}
Marc Gravell
Whilst this code will work, is that the normal operation of a CancelEventHandler? Aren't they usually used in a BeforeX, AfterX pattern, where if anything in Before sets Canel, then X doesn't happen so AfterX doesn't get called. Why is it important to stop other listeners getting the Before event?
Sam Meldrum