November 2, 2009

Debugging event subscriptions in C#/.NET

Recently I had to debug a problem around events. I wanted to find out which objects are subscribing to a certain event and when. As there is no code in the class that handles the event subscription, you cannot set a breakpoint there. Too bad...

But there's a simple way out of this. Let's assume you have a class like this:


class Test : INotifyPropertyChanged
{

public event PropertyChangedEventHandler PropertyChanged = delegate { };

void FirePropertyChanged(string property)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}


You can add a "custom event implementation" that forwards all event subscriptions and un-subscriptions to a private event, similar to a property that uses a private field to store its value:


class Test : INotifyPropertyChanged
{

private event PropertyChangedEventHandler propertyChangedImpl = delegate { };
public event PropertyChangedEventHandler PropertyChanged
{
add { this.propertyChangedImpl += value; }
remove { this.propertyChangedImpl -= value; }
}

void FirePropertyChanged(string property)
{
this.propertyChangedImpl(this, new PropertyChangedEventArgs(property));
}
}


The you can simply set the breakpoint to the add method and see exactly where and when these event registrations happen.
blog comments powered by Disqus