简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM