views:

82

answers:

3
+1  Q: 

C# event handlers

Is there a way to get number of attached event handlers to event? The problem is that somewhere in code it continues to attach handlers to an event, how can this be solved?

A: 

You can implement your own event add/remove methods:

private EventHandler _event;

public event EventHandler MyEvent
{
  add 
  { 
    if (_event == null) _event = value;
    _event += value; 
  }  

  remove 
  {
    if (_event != null) _event -= value;
  }
}
Mark Cidade
+5  A: 

It is possible to get a list of all subscribers by calling GetInvocationList()

public class Foo
{
    public int GetSubscriberCount()
    {
        var count = 0;
        var eventHandler = this.CustomEvent;
        if(eventHandler != null)
        {
            count = eventHandler.GetInvocationList().Length;
        }
        return count;
    }

    public event EventHandler CustomEvent;
}
Rohan West
A: 

You can overwrite the add- and remove- operation (+= and -=) for the Event as seen in the following code:

private int count = 0;
public event EventHandler MyEvent {
    add {
        count++;
        // TODO: store event receiver
    }
    remove {
        count--;
        // TODO: remove event receiver
    }
}
Jens Nolte