views:

223

answers:

1

Similar to the KeyPress events, I want whoever is subscribed to the event to be able to set e.Handled in my EventArgs class. If they return true, I no longer want to continue firing events. Any ideas how to implement this? Right now, here is my method:

protected void OnDataReceived(SocketAsyncEventArgs e)
{
    if (DataReceived != null)
    {                
        DataReceived(this, e);
    }
}

From my understanding, everybody who is subscribed to the event will receive notification, so setting e.Handled = true; will have no effect here.

+3  A: 

Sample code for a solution using Delegate.GetInvocationList:

public class MyEventArgs : EventArgs
{
    public bool Handled { get; set; }
}

public class SomeClass
{
    public event EventHandler<MyEventArgs> SomeEvent;

    protected virtual void OnSomeEvent(MyEventArgs e)
    {
        var listeners = SomeEvent.GetInvocationList();
        foreach (var listener in listeners)
        {
            if (e.Handled) break;
            ((EventHandler<MyEventArgs>)listener).Invoke(this, e);
        }
    }
}
Tormod Fjeldskår