2

While debugging in Visual Studio 2013, I'd like to know the number of subscribers to the event PropertyChanged published by a certain class (let's call it Publisher) that implements INotifyPropertyChanged.

I've researched a bit and found that this should be possible calling GetInvocationList() and counting the elements in the returned array. So I've set a breakpoint in my code and tried to call this on an object called publisher of class Publisher in the Immediate window:

publisher.PropertyChanged.GetInvocationList()

However, I get this error message:

The event 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' can only appear on the left hand side of += or -=

What's wrong with what I've done? How can I access the subscribers to PropertyChanged?

elnigno
  • 1,751
  • 14
  • 37

2 Answers2

5

How can I access the subscribers to PropertyChanged?

You don't, basically. An event only supports subscribe and unsubscribe functionality.

I've researched a bit and found that this should be possible calling GetInvocationList() and counting the elements in the returned array.

That assumes you can get at the underlying delegate field - if there even is one. There might not be - there are lots of ways an event can be implemented, just like there are lots of ways a property can be implemented.

Basically, what you're asking for breaks the encapsulation model of events. While there are ways around this in certain situations using reflection, you should be aware that you're fighting the design of the system.

See my article on events and delegates for more about the differences between the two.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

What you are asking to do is not simple at all. And there is no standard way to do it - basically you can hack existing implementations but the solution is not guaranteed to work in the future.

I managed to read subscribers to an event and this is the root URL of the project: http://www.codinghelmet.com/?path=net/sysexpand/reflection

Starting point from which you can find where I was iterating through the subscribers is to look for the AddMonitoredObject method on this page: http://www.codinghelmet.com/?path=net/sysexpand/reflection/source/dynevsubscr

Hope this helps. But keep in mind that this solution is a hack.

Zoran Horvat
  • 10,924
  • 3
  • 31
  • 43