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 coun开发者_如何转开发t 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.
You can use GetInvocationList()
:
MessageReceived?.GetInvocationList().Length
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 += ...;
}
}
精彩评论