Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement a cancelable event?

Tags:

c#

events

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?

like image 591
Simon Avatar asked Nov 17 '08 10:11

Simon


People also ask

What are cancelable events?

Definition and Usage The event is cancelable if it is possible to prevent the events default action.

Is cancelable a word?

The word cancellable (which is also but less commonly spelled cancelable) describes something, such as a contract or policy, that can be canceled—that is, that can be made no longer valid or effective.

Why we use jQuery to wire up events?

jQuery makes it straightforward to set up event-driven responses on page elements. These events are often triggered by the end user's interaction with the page, such as when text is entered into a form element or the mouse pointer is moved.

How do you remove a listener?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.


1 Answers

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) { /* ... */ }
    }
}
like image 76
Marc Gravell Avatar answered Sep 28 '22 11:09

Marc Gravell