How to find out how many event handlers for an event?

How to find out how many event handlers for an event?

I need a way to execute the following code:

// if (control.CheckedChanged.Handlers.Length == 0) { control.CheckedChanged += (s, e) => { // code; } } 

Note: this code is outside the management class.

Thanks in advance.

+4
source share
2 answers

You cannot, because only the type that the event provides has access to the actual delegate. From inside the control, you can do something like this:

 if (MyEvent!= null) { EventHandler[] handlers = (EventHandler[])MyEvent.GetInvocationList(); foreach(EventHandler handler in handlers) { ... } } 

Or what you are trying to do:

 if (CheckedChanged == null) { CheckedChanged += (s, e) => { // code; } } 
+3
source

My answer is more likely a comment for Thomas Levesque, but I cannot comment, so nothing happens here. I find this C # area a little ugly, as it’s possible to enter race conditions - that is, different threads can participate in the race, and you can enter the if using CheckedChanged != null

 if (CheckedChanged == null) { CheckedChanged += (s, e) => { // code; } } 

You must either block this code, but in many cases you will find that you are writing such code

 //Invoke SomeEvent if there are any handlers attached to it. if(SomeEvent != null) SomeEvent(); 

But SomeEvent can be zeroed out in the process, so it would be safer to write something like this

 SomeEVentHandler handler = SomeEvent; if (handler != null) handler(); 

... just be more secure.

+1
source

All Articles