Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 573
Viktor Avatar asked Dec 29 '22 07:12

Viktor


1 Answers

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;
}
like image 71
Rohan West Avatar answered Jan 06 '23 08:01

Rohan West