Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I track subscribers to an event in C#?

Is there some hidden class property which would allow to know this ?

like image 945
user310291 Avatar asked Feb 06 '11 01:02

user310291


1 Answers

If you have access to the actual delegate (if you're using the shorthand event syntax, then this is only within the actual declaring class, as the delegate is private), then you can call GetInvocationList().

For instance:

public event EventHandler MyEvent;

To get the list of subscribers, you can call:

Delegate[] subscribers = MyEvent.GetInvocationList();

You can then inspect the Method and Target properties of each element of the subscribers array, if necessary.

The reason this works is because declaring the event as we did above actually does something akin to this:

private EventHandler myEventDelegate;

public event EventHandler MyEvent
{
    add { myEventDelegate += value; }
    remove { myEventDelegate -= value; }
}

This is why the event looks different when viewed from within the declaring class compared to anywhere else (including classes that inherit from it). The only public-facing interface is the add and remove functionality; the actual delegate, which is what holds the subscriptions, is private.

like image 58
Adam Robinson Avatar answered Oct 16 '22 19:10

Adam Robinson