Search code examples
c#eventssubscriptioneventtrigger

How to easilly see number of event subscriptions while debugging?


While debugging, can I look into textBox1.TextChanged to see the number of event subscriptions? If yes, then how do I drill to it? I need to know how many subscriptions there are at a given time for debugging because it looks like an event is triggered multiple times, but I suspect this bug is really because textBox1.TextChanged += handler is being mismanaged in the application, so there are too many subscribers.

Here is a simplified version of what I think is happening. If possible, I just want to set a breakpoint and count up the number of subscriptions to "textBox1.TextChanged":

private void textBox1_TextChanged(object sender, EventArgs e)
{
    textBox1.TextChanged += textBox1_TextChanged;
    MessageBox.Show("asdf");
    textBox1.TextChanged -= textBox1_TextChanged;        
    textBox1.Text = DateTime.Now.ToString();
    textBox1.TextChanged += textBox1_TextChanged;
}

Is that possible or is it more complicated?


Solution

  • You will have to use Reflection to get to the invocation list of the event delegate:

        textBox1.TextChanged += textBox1_TextChanged;
        MessageBox.Show("asdf");
        textBox1.TextChanged -= textBox1_TextChanged;        
        textBox1.Text = DateTime.Now.ToString();
        textBox1.TextChanged += textBox1_TextChanged;
        var eventField = textBox1.GetType().GetField("TextChanged", BindingFlags.GetField
                                                                   | BindingFlags.NonPublic
                                                                   | BindingFlags.Instance);
    
        var subscriberCount = ((EventHandler)eventField.GetValue(textBox1))
                    .GetInvocationList().Length;