Viktor
Viktor

Reputation: 702

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?

Upvotes: 4

Views: 4049

Answers (3)

Jens Nolte
Jens Nolte

Reputation: 509

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
    }
}

Upvotes: 0

Rohan West
Rohan West

Reputation: 9308

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;
}

Upvotes: 10

Mark Cidade
Mark Cidade

Reputation: 100047

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;
  }
}

Upvotes: 0

Related Questions