usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26874

How to count how many listeners are hooked to an event?

Assuming I have declared

public event EventArgs<SyslogMessageEventArgs> MessageReceived;

public int SubscribedClients
{
    get [...]
}

I would like to count how many "subscribed clients" my class has. I need to sum those that subscribed over network though my APIs (not shown in the fragment) plus those that did channel.MessageReceived+=myMethod;.

I know that C# events may be declared explicitly with add and remove statements, and there I can surely count + or -1 to a local counter, but I never wrote code for explicit events in C#, so I don't know exactly what more to perform on add and remove rather than updating the counter.

Thank you.

Upvotes: 45

Views: 32547

Answers (2)

Max-xaM
Max-xaM

Reputation: 11

class A
{
   public event EventArgs<SyslogMessageEventArgs> MessageReceived;

   public int SubscribedClients
   {
       get {
         return (MessageReceived == null)
                ? 0
                : MessageReceived.GetInvocationList().Length
                ;
       }
   } 
}


void Main()
{
    A a = new A();
    if(a.SubscribedClients == 0)
    {
        a.MessageReceived += ...;
    }
}

Upvotes: 1

Andrey
Andrey

Reputation: 60065

You can use GetInvocationList():

MessageReceived?.GetInvocationList().Length

Upvotes: 89

Related Questions