Checking for event handlers

  • Thread starter Thread starter Darren
  • Start date Start date
Darren said:
Is there any way to check to see if there are any handlers registered
for a given event?

Well, I have something in VB, hope this helps:

Public Class Blah
Public Shared Event InstanceAdded(ByVal sender as Object,ByVal e as
EventArgs)

Private Sub ClearCaches(ByVal OldState as CCOptions,ByVal NewState as
CCOptions)
If ((OldState Xor NewState) And CCOptions.CacheCollections) <> 0
Then
lstCache.Clear()
End If
If ((OldState Xor NewState) And CCOptions.CacheUpdateEvents) <> 0
Then
If Not InstanceAddedEvent is Nothing Then
For Each rb as System.Delegate in
InstanceAddedEvent.GetInvocationList()
RemoveHandler
InstanceAdded,DirectCast(rb,InstanceAddedEventHandler)
Next
End If
End If
End Sub
End Class

As you can see, VB creates a member called <Event Name>Event for each
event you declare. If someone has attached an event handler, then it
will be set to a <Event Name>EventHandler (which derives from
EventHandler). You can then query it's invocation list to get each
subscriber to the event.

HTH,

Damien
 
Just check if the event instance is null, like
delegate void SomeDelegate(object sender, EventArgs e)

class Test
{
event SomeDelegate SomeEvent;

bool AreHandlersRegistered()
{
return SomeEvent != null;
}
}

Regards
Senthil
 
Back
Top