Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

events

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.

like image 489
usr-local-ΕΨΗΕΛΩΝ Avatar asked Oct 30 '10 12:10

usr-local-ΕΨΗΕΛΩΝ


People also ask

How do you find attached event listeners?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

Can multiple listeners be attached to an event?

You can do how ever you want it to do. They don't have to be together, it depends on the context of the code. Of course, if you can put them together, then you should, as this probably makes the structure of your code more clear (in the sense of "now we are adding all the event handlers").

Why should you remove event listeners once they are no longer used?

The event listeners need to be removed due to following reason. Avoid memory leaks, if the browser is not handled it properly. Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

How do event listeners work?

Often an event listener is registered with the object that generates the event. When the event occurs, the object iterates through all listeners registered with it informing them of the event.


1 Answers

You can use GetInvocationList():

MessageReceived?.GetInvocationList().Length 
like image 147
Andrey Avatar answered Sep 21 '22 07:09

Andrey