Search code examples
c#event-handling

How events like CancelEventArgs can be used with multiple subscribers?


How can the event System.ComponentModel.CancelEventArgs be used? Suppose we have the following code:

    public event CancelEventHandler EventTest = delegate { };

    public void MakeSomethingThatRaisesEvent()
    {
        CancelEventArgs cea = new CancelEventArgs();
        EventTest(this, cea);
        if (cea.Cancel)
        {
            // Do something
        }
        else
        {
            // Do something else
        }
    }

What happens if more than one delegate is registered on the event? There is any way to get the results of all the subscribers?

This is used on Winforms (at least) sometimes. If not possible to get all values, they suppose only one subscriber to the event?


Solution

  • To ask each subscriber separately, you need to access the list:

    foreach (CancelEventHandler subHandler in handler.GetInvocationList())
    {
         // treat individually
    }
    

    Then you can check each in turn; otherwise you just get the final vote.