Alex Rivera | Logout

How do you find out what is subscribed to an event in C#?

Asked 2010-12-09T15:55:22.450
11

I'm having a problem where an application I'm working on has memory leaks. Experience has taught me that one of the first places garbage collected languages experience memory leaks is dealing with subscribing to events and failing to unsubscribe them later. The second has to do with storing static state. I'm new to C# and have been frustrated by the opaque event type.

We've caught a few double subscription errors through luck of the draw, but the application really uses events for a number of things. While we are well aware of the principle of unsubscribing everything you subscribe to, there's still memory leaks. I'd like to systematically determine what's subscribed to what.

Edit:

Thank you for the pointer to the GetInvocationList() method. I'm trying to create a debug harness that will dump the results dynamically. Problem is that the solutions I found worked in .Net 2, but no longer in .Net 3.5. Essentially, the tell you to get the corresponding FieldInfo for the EventInfo (reflection, GetField and GetEvents respectively). However, in .Net 3.5 there is no corresponding FieldInfo, and EventInfo won't let me get the invocation list.

I just want to dump the list of events and their InvocationList for debugging purposes.

Edit
Report

1 Answer

7

Try to use an method on the event called GetInvocationList.

This will return an array of delegates that is subscribing to the event.

The array will contain the delegates in the order they where added. This can also be used to single out and invoking specific delegates from the list, whereas calling the event.Invoke method will invoke them all (but only give you the return value of the last delegate called)

answered 2010-12-09T15:57:36.257

Your Answer