导航

How do I implement a cancelable event?

Posted on 2015-04-29 10:31  eastson  阅读(118)  评论(0编辑  收藏  举报

n 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?

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) { /* ... */ }
    }
}

http://stackoverflow.com/questions/295254/how-do-i-implement-a-cancelable-event